How to randomly interchange values in different rows in a matrix

1 view (last 30 days)
Hello,
I have a matrix, say A = [1 2 3 4 5;6 7 8 9 10]. I would like to randomly pick a cutpopint for each row and then swap the elements. Here is my script:
for row = 1:size(A,1)
cutpoint = randsample(size(A,2),1);
B(row,:) = A(row, [cutpoint:end 1:cutpoint-1]);
end
I was wondering if there is a neat way to skip to the loop, because my matrix is huge and I have to repeat the cut-and-swap procedure on the matrix 1000 times. This is really time consuming.
Any help is much appreciated.
Best,
Shen-Mou

Accepted Answer

Matt J
Matt J on 5 Mar 2019
Edited: Matt J on 5 Mar 2019
[m,n] = size(A);
shuffle=mod( randi([0,n-1],m,1)+(0:n-1) , n )*m +(1:m).',
B=A(shuffle),
  7 Comments
Matt J
Matt J on 6 Mar 2019
Edited: Matt J on 6 Mar 2019
You should upgrade your Matlab version to avoid that and to simplify your code, but if you cannot upgrade then you can re-implement as follows
z = bsxfun(@plus, randi([0,n-1],m,1) , (0:n-1) );
shuffle=bsxfun(@plus, mod(z,n)*m , (1:m).') ;

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 5 Mar 2019
Edited: Andrei Bobrov on 5 Mar 2019
[m,n] = size(A);
At = A.';
[~,ii] = sort(rand([n,m]));
cutpoint = find(ii == 1);
i0 = zeros([n,m]);
i0(1,:) = 1;
i0(ccutpoint) = -1;
I = cumsum(i0);
I(:,I(1,:) == -1) = 0;
[~,ii] = sort(I);
B = At(ii + (0:m-1)*n).';

Categories

Find more on Automotive in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!