Sort array elements in ascending order
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Pankaja Tanjore
el 18 de Feb. de 2015
Hello,
I have an input array which i want to sort column elements in ascending order
i =
[4 35;
2 4;
2 6 ;
1 9;
4 3 ;
4 6 ;
1 16;
3 17];
and get the sorted output array in the following manner
res=
[1 9;
1 16;
2 4;
2 6;
3 17;
4 3;
4 6;
4 35];
First sort according to the 1st column(ascending order),if the first column is same then check for the second column ,then sort in the acending order based on the second value.
For example : I have 1 as the least value in the first column and have two entries for 1. So check for the second element for 1. I have 9 and 16 as the second element for 1 respectively.Now sort these second elemnts in ascending order.so i have the output as [1 9; 1 16] .
Similary for all the other elements of the matrix.
Please let me know the MATLAB function for sorting the array elements and get me the required output as mentioned above.
Looking forward to hear from you
Thanks Pankaja
0 comentarios
Respuesta aceptada
Stephen23
el 18 de Feb. de 2015
Editada: Stephen23
el 18 de Feb. de 2015
You can sort the rows and extract the minimum value of each "group" like this:
>> A = [8 4; 3 6; 2 7; 1 4; 2 3;2 1;3 1; 3 5; 8 6; 8 1];
>> B = sortrows(A);
>> X = [true;diff(B(:,1))>0];
>> B(X,:)
ans =
1 4
2 1
3 1
8 1
Where each row is the "minimum" of each group.
4 comentarios
Stephen23
el 19 de Feb. de 2015
Editada: Stephen23
el 19 de Feb. de 2015
If you define exactly what the "difference" between two differently-dimensioned matrices is, then I will show you how to code it.
Your matrices have a different number of rows: what are we supposed to subtract the un-matched row from? Lets look at your matrices in detail:
A - B = C
[1 4; [1 6; = [0 -2;
2 1; 2 1; 0 0;
3 1; 2 5; 1 -4;
8 1] 3 0; 5 1;
8 1] <- what are we supposed to subtract this from?
Más respuestas (1)
Ilham Hardy
el 18 de Feb. de 2015
res = sortrows(i,[1,2]);
PS: Don't name you variable i, by the way.
i in matlab represent sqrt(-1)
1 comentario
Ver también
Categorías
Más información sobre Matrices and Arrays 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!