Rearrange elements of matrix based on an index matrix
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hossein Kazemi
el 27 de Ag. de 2024
Comentada: Hossein Kazemi
el 27 de Ag. de 2024
I have a 5x3 matrix and I want to rearrange each row according to the correponding row of a 5x3 index matrix
x=randn(5,3)
z=randn(5,3)
[~,I]=sort(x,2)
Now I want to sort rows of z using the index matrix I. But using the following does not work. For example, I want the first row of zz to be sorted according to the first row of x, which should result in zz(1,:)= [1.3644, -0.1687, 0.4662].
zz=z(I)
0 comentarios
Respuesta aceptada
Stephen23
el 27 de Ag. de 2024
Editada: Stephen23
el 27 de Ag. de 2024
Yes, it is awkward.
x=randn(5,3)
z=randn(5,3)
[~,I] = sort(x,2)
Perhaps
S = size(I);
[R,~] = ndgrid(1:S(1),1:S(2));
J = sub2ind(S,R,I);
zz = z(J)
Or
zz = z;
for k = 1:size(I,1)
zz(k,:) = zz(k,I(k,:));
end
zz
Or
zz = cell2mat(cellfun(@(v,x)v(x),num2cell(z,2),num2cell(I,2),'uni',0))
Más respuestas (0)
Ver también
Categorías
Más información sobre Operating on Diagonal Matrices 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!