How to randomly interchange values in different rows in a matrix

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

[m,n] = size(A);
shuffle=mod( randi([0,n-1],m,1)+(0:n-1) , n )*m +(1:m).',
B=A(shuffle),

7 Comments

Many thanks for all your help! Unfortunately, they do not work in my real case, as the data are complex values. Just wondered if there is a built-in function for this!
Well, why don’t you say it in the first place while asking?
I don't see why complex data invalidates the solution. They should be re-ordered just the same.
Hi Matt,
Indeed, my misunderstanding! Yours is a general solution to my question. Many thanks again!
BTW, when I ran this part of the code "randi([0,n-1],m,1)+(0:n-1)", it returned: "Error using + Matrix dimensions must agree". Did I miss something?
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)

[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 MATLAB in Help Center and File Exchange

Tags

Asked:

on 5 Mar 2019

Commented:

on 11 Mar 2019

Community Treasure Hunt

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

Start Hunting!