# All negative number on bottom

7 visualizaciones (últimos 30 días)
Andrea Stevanato el 7 de Mayo de 2018
Editada: Stephen23 el 7 de Mayo de 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 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Stephen23 el 7 de Mayo de 2018
Editada: Stephen23 el 7 de Mayo de 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 comentariosMostrar NingunoOcultar Ninguno
Andrea Stevanato el 7 de Mayo de 2018
Could you give me a simple explanation of why it works?
Stephen23 el 7 de Mayo de 2018
Editada: Stephen23 el 7 de Mayo de 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

Iniciar sesión para comentar.

### Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

### Community Treasure Hunt

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

Start Hunting!

Translated by