How to swap specific elements position of a matrix

1 view (last 30 days)
Jenjen Ahmad Zaeni on 2 May 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.

DGM on 2 May 2021
The problem is a bit underdefined. I'm going to make the following assumptions:
• There are always exactly two nonzero elements per column
• The goal is to merely swap the nonzero elements in each column regardless of sorting
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
Jenjen Ahmad Zaeni on 24 May 2021
I've tried this with other random value and it works perfectly like this. Once again, thank you very much. Have a great day.
>> A
A =
0 25.5540 -227.4337 -25.5540 227.4337 1.4323 0
0 -257.3220 0 0 0 -269.4361 227.4337
52.9148 272.7692 0 0 -257.3220 -1.4323 257.3220
0 0 -233.1677 -1.4323 0 0 0
257.6266 -32.0834 269.4361 -25.5540 -269.4361 0 0
>> B
B =
0 -32.0834 269.4361 -25.5540 -269.4361 -1.4323 0
0 272.7692 0 0 0 -269.4361 257.3220
257.6266 -257.3220 0 0 -257.3220 1.4323 227.4337
0 0 -233.1677 -1.4323 0 0 0
52.9148 25.5540 -227.4337 -25.5540 227.4337 0 0

R2014a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by