How to randomly interchange values in different rows in a matrix
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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),
More Answers (1)
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).';
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!