nofunsally
nofunsally

Reputation: 2091

Permute elements within rows of matrix

I have a matrix A

A = [0 0 0 0 1; 0 0 0 0 2; 0 1 2 3 4];

and I would like to randomly permute the elements within each row. For example, matrix A2

A2 = [1 0 0 0 0; 0 0 0 2 0; 4 1 3 2 0]; % example of desired output

I can do this with a vector:

Av = [0 1 2 3 4];
Bv = Av(randperm(5));

But I am unsure how to do this a row at time for a matrix and to only permute the elements within a given row. Is this possible to do? I could construct a matrix from many permuted vectors, but I would prefer not to do it this way.

Thanks.

Upvotes: 2

Views: 4280

Answers (1)

Jonas
Jonas

Reputation: 74940

You can use sort on a random array of any size (which is what randperm does). After that, all you need to do is some index-trickery to properly reshuffle the array

A = [0 0 0 0 1; 0 0 0 0 2; 0 1 2 3 4];
[nRows,nCols] = size(A);

[~,idx] = sort(rand(nRows,nCols),2);

%# convert column indices into linear indices
idx = (idx-1)*nRows + ndgrid(1:nRows,1:nCols);

%# rearrange A
B = A;
B(:) = B(idx)

B =

     0     0     1     0     0
     0     2     0     0     0
     2     1     3     4     0

Upvotes: 6

Related Questions