All negative number on bottom

3 Ansichten (letzte 30 Tage)
Andrea Stevanato
Andrea Stevanato am 7 Mai 2018
Bearbeitet: Stephen23 am 7 Mai 2018
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]

Akzeptierte Antwort

Stephen23
Stephen23 am 7 Mai 2018
Bearbeitet: Stephen23 am 7 Mai 2018
>> 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 Kommentare
Andrea Stevanato
Andrea Stevanato am 7 Mai 2018
Could you give me a simple explanation of why it works?
Stephen23
Stephen23 am 7 Mai 2018
Bearbeitet: Stephen23 am 7 Mai 2018
@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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by