- There are always exactly two nonzero elements per column
- The goal is to merely swap the nonzero elements in each column regardless of sorting
How to swap specific elements position of a matrix
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jenjen Ahmad Zaeni
el 2 de Mayo de 2021
Comentada: Jenjen Ahmad Zaeni
el 24 de Mayo de 2021
Hello everyone. I have a matrix like A = [ 1 0 0 2; 0 3 4 0; 5 6 0 0; 0 0 7 8 ]
I want a new matrix like B = [ 5 0 0 8; 0 6 7 0; 1 3 0 0; 0 0 4 2 ]
Is it possible to do that? Thank you.
0 comentarios
Respuesta aceptada
DGM
el 2 de Mayo de 2021
The problem is a bit underdefined. I'm going to make the following assumptions:
A = [ 1 0 0 2; 0 3 4 0; 5 6 0 0; 0 0 7 8 ]
% assuming there are exactly two nonzero elements per column
nz = sort(A,1);
B = zeros(size(A));
B(A~=0) = flipud(nz(end-1:end,:))
gives
A =
1 0 0 2
0 3 4 0
5 6 0 0
0 0 7 8
B =
5 0 0 8
0 6 7 0
1 3 0 0
0 0 4 2
4 comentarios
DGM
el 24 de Mayo de 2021
Editada: DGM
el 24 de Mayo de 2021
If the number of nonzero elements varies per column, it gets a bit more complicated. This might be able to be simplified, but I just used a loop and logical indexing.
A = [-225.2565 0 0 226.1974 -225.2565 225.2565 0;
-225.2565 0 225.2565 226.1974 0 0 -225.2565;
0 -257.1251 248.9089 0 0 248.9089 -248.9089;
20.8466 0 0 -29.3149 20.8466 0 20.8466;
0 -219.0711 0 218.4656 0 218.4656 -218.4656];
B = zeros(size(A));
for n = 1:size(A,2)
m = A(:,n)~=0;
B(m,n) = flipud(A(m,n));
end
B
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing 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!