- 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 views (last 30 days)
Show older comments
Jenjen Ahmad Zaeni
on 2 May 2021
Commented: Jenjen Ahmad Zaeni
on 24 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.
0 Comments
Accepted Answer
DGM
on 2 May 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 Comments
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
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!