Sort array elements in ascending order
8 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2015-2-18
编辑:Stephen23
2015-2-18
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 个评论
Stephen23
2015-2-19
编辑:Stephen23
2015-2-19
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?
更多回答(1 个)
Ilham Hardy
2015-2-18
res = sortrows(i,[1,2]);
PS: Don't name you variable i, by the way.
i in matlab represent sqrt(-1)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!