All negative number on bottom

3 次查看(过去 30 天)
How i can sort matrix of numbers and put negative on bottom respecting the order of positive elements.
A = [1,-3,4;-2,5,6;4,2,1]
newA = [1,5,4;4,2,6;-2,-3,1]

采纳的回答

Stephen23
Stephen23 2018-5-7
编辑:Stephen23 2018-5-7
>> A = [1,-3,4;-2,5,6;4,2,1]
A =
1 -3 4
-2 5 6
4 2 1
>> S = size(A);
>> [~,R] = sort(A<0,1);
>> C = ones(S(1),1)*(1:S(2));
>> X = sub2ind(S,R,C);
>> A(X)
ans =
1 5 4
4 2 6
-2 -3 1
  2 个评论
Andrea Stevanato
Andrea Stevanato 2018-5-7
Could you give me a simple explanation of why it works?
Stephen23
Stephen23 2018-5-7
编辑:Stephen23 2018-5-7
@Andrea Stevanato: basically we first detect the locations of the negative values, sort those locations, then create linear indices from those sorted locations. Lets have a look:
>> A = [1,-3,4;-2,5,6;4,2,1]
A =
1 -3 4
-2 5 6
4 2 1
>> S = size(A);
>> A<0 % logical index of negative values.
ans =
0 1 0
1 0 0
0 0 0
>> [~,R] = sort(A<0,1) % sort the columns of the logical index, returns row indices of each sorted column.
R =
1 2 1
3 3 2
2 1 3
>> C = ones(S(1),1)*(1:S(2)) % define column indices.
C =
1 2 3
1 2 3
1 2 3
>> X = sub2ind(S,R,C) % linear indices from row and column indices.
X =
1 5 7
3 6 8
2 4 9
>> A(X) % get elements of A using linear indices.
ans =
1 5 4
4 2 6
-2 -3 1

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by