필터 지우기
필터 지우기

All negative number on bottom

조회 수: 3 (최근 30일)
Andrea Stevanato
Andrea Stevanato 2018년 5월 7일
편집: Stephen23 2018년 5월 7일
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