Sort array elements in ascending order
조회 수: 6 (최근 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!