MATLAB Answers


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

Asked by Yuval
on 27 Mar 2013
Accepted Answer by Matt J

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) = [];



No products are associated with this question.

1 Answer

Answer by Matt J
on 27 Mar 2013
Edited by Matt J
on 27 Mar 2013
 Accepted answer

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


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.


on 27 Mar 2013

Is it "legal" that my code changes the original vector?

Matt J
on 27 Mar 2013

Only you and presumably the instructor who assigned this to you can know what is "legal" for you.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!