All negative number on bottom
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Andrea Stevanato
il 7 Mag 2018
Modificato: Stephen23
il 7 Mag 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]
0 Commenti
Risposta accettata
Stephen23
il 7 Mag 2018
Modificato: Stephen23
il 7 Mag 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 Commenti
Stephen23
il 7 Mag 2018
Modificato: Stephen23
il 7 Mag 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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!