How do I repetitively shuffle elements in my matrix column-wise?
17 views (last 30 days)
Show older comments
Hello everyone,
I am new to MATLAB and have a question about how to randomly shuffle elements in a matrix column-wise. Specifically, I have a 582x255 matrix and I would like to shuffle the elements. However, it is important that the elements of one column stay in the same column, so a column-wise shuffle and that the every column is shuffled in a different way (so that the elements in one row are not all shuffled to the same row). So far, this is what I have come up with:
[m,n]=size(F); % F = 582x255 matrix
nb_rows = n; %number of rows
C_1 = F(:,1); % select first column of matrix
C_1_s = C_1(randperm(length(C_1))); % randomly shuffle the elements of that column
This works. However, I would like to find a way to do it automatically for every column. I think I would need to create a loop that does the same thing column per column, so I have tried this:
for i=1:nb_rows;
C_i = F(i,1);
C_i_s = C_i(randperm(length(C_i)));
end
But it doesn't seem to work.
I would greatly appreciate it if someone could help me with this!
0 Comments
Accepted Answer
Matt J
on 8 Jan 2024
Edited: Matt J
on 8 Jan 2024
F=magic(5)
[m,n]=size(F);
[~,I]=sort(rand([m,n]));
J=repmat(1:n,m,1);
Fshuffle = F(sub2ind([m,n],I,J))
6 Comments
Matt J
on 10 Jan 2024
Edited: Matt J
on 10 Jan 2024
That works perfectly, thank you very much!
You're welcome, but please Accept-click the answer to indicate that it worked.
I have one last question: is there a way to repeat this loop a 100 times so that I get 100 variables each which a different shuffle of the matrix?
As below:
F=magic(5)
[m,n]=size(F);
p=100;
[~,I]=sort(rand([m,n,p]));
J=repmat(1:n,m,1,p);
Fshuffle = F(sub2ind([m,n],I,J))
More Answers (1)
Voss
on 8 Jan 2024
Looks like this is what you are going for:
[m,n]=size(F); % F = 582x255 matrix
for i = 1:n
C_i = F(:,i);
C_i_s = C_i(randperm(m));
F(:,i) = C_i_s;
end
And it can be written more succinctly wihout the temporary variables:
[m,n]=size(F); % F = 582x255 matrix
for i = 1:n
F(:,i) = F(randperm(m),i);
end
2 Comments
Voss
on 9 Jan 2024
It is one matrix. Each column of F is shuffled separately one time and stored back in F.
See Also
Categories
Find more on Logical 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!