How to swap specific elements position of a matrix

3 次查看(过去 30 天)
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
DGM 2021-5-2
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 个评论
DGM
DGM 2021-5-24
编辑:DGM 2021-5-24
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 2021-5-24
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by