How do I repetitively shuffle elements in my matrix column-wise?
16 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Matt J
2024-1-8
编辑:Matt J
2024-1-8
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 个评论
Matt J
2024-1-10
编辑:Matt J
2024-1-10
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))
更多回答(1 个)
Voss
2024-1-8
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 个评论
Voss
2024-1-9
It is one matrix. Each column of F is shuffled separately one time and stored back in F.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!