How to swap specific elements position of a matrix

3 views (last 30 days)
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.

Accepted Answer

DGM
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
  4 Comments
DGM
DGM on 24 May 2021
Edited: DGM on 24 May 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
B = 5×7
20.8466 0 0 218.4656 20.8466 218.4656 0 -225.2565 0 248.9089 -29.3149 0 0 -218.4656 0 -219.0711 225.2565 0 0 248.9089 20.8466 -225.2565 0 0 226.1974 -225.2565 0 -248.9089 0 -257.1251 0 226.1974 0 225.2565 -225.2565
Jenjen Ahmad Zaeni
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

Sign in to comment.

More Answers (0)

Products


Release

R2014a

Community Treasure Hunt

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

Start Hunting!