How to mix order of rows in a matrix?

5 views (last 30 days)
With randperm it is possible to mix order of the components of a vector v: v(randperm(lenght(v)))
But how to mix rows in a matrix?

Accepted Answer

Jos (10584)
Jos (10584) on 25 Feb 2015
Very much the same procedure;
M = repmat(1:10,4,1).' % example data
r = randperm(size(M,1)) % permute row numbers
Mout = M(r,:)
  4 Comments
Mr M.
Mr M. on 25 Feb 2015
but I need the same permutation used for the matrix rows!
Stephen23
Stephen23 on 25 Feb 2015
Assuming that your matrix has the same number of rows as your vector has elements, then you just need to use the same indices for both the matrix and the vector:
r = randperm(size(M,1)) % generate your indices.
Mout = M(r,:) % rearrange the rows of a matrix
Vout = V(r) % rearrange the elements of a vector
Look how they both use the same permutation r. You should read about indexing.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!