Filter löschen
Filter löschen

How to permute a row vector without using perms(), permute() etc.

1 Ansicht (letzte 30 Tage)
Yuval
Yuval am 27 Mär. 2013
I would like to permute a row vector, but without using perms(), permute() and so forth. I was wondering whether the following code answers these requirements. I mean, am I somewhat "cheating" by using randi()? I'd also appreciate any comments on the algorithm in general (although I know the function works well).
function Y = ex(X)
Y = zeros(1,length(X));
for i = 1:length(X)
d = randi(length(X));
Y(i) = X(d);
X(d) = [];
end

Akzeptierte Antwort

Matt J
Matt J am 27 Mär. 2013
Bearbeitet: Matt J am 27 Mär. 2013
It doesn't violate any requirements that you've mentioned, so I'm inclined to say it's legal. Here's another way, if you don't like randi for some reason
n=length(X);
[~,~,e]=qr(sprand(n,n,1/n));
Y=reshape(e*X(:),size(X)),
If the permuted order is supposed to be random, I don't think there's any avoiding the use some sort of random number generator.
  2 Kommentare
Yuval
Yuval am 27 Mär. 2013
Bearbeitet: Yuval am 27 Mär. 2013
Is it "legal" that my code changes the original vector?
Matt J
Matt J am 27 Mär. 2013
Only you and presumably the instructor who assigned this to you can know what is "legal" for you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by