How do I repetitively shuffle elements in my matrix column-wise?
18 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Joyce Oerlemans
el 8 de En. de 2024
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 comentarios
Respuesta aceptada
Matt J
el 8 de En. de 2024
Editada: Matt J
el 8 de En. de 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 comentarios
Matt J
el 10 de En. de 2024
Editada: Matt J
el 10 de En. de 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))
Más respuestas (1)
Voss
el 8 de En. de 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 comentarios
Voss
el 9 de En. de 2024
It is one matrix. Each column of F is shuffled separately one time and stored back in F.
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!