I have an array with the first column being x-coordinate, the second column being y-coordinate and then the next few columns being different values. I've used an if function so that all the y-coordinates are the same in the array but I then want to sort by x-coordinate (so my plot(x,y) is in order rather than jumping all over the place). The problem is that when I use the sort() function, it orders all my other columns too so the data is no longer associated with the correct coordinate.
Annotation 2019-03-17 123107.jpg
This is a copy of the data unsorted.
Annotation 2019-03-17 123143.jpg
This is after I've used the sort function. It also sorts column 3 which I don't want to happen. I want the 58.6480 value (column 3) to remain in the same row as the 20 value from column 1.

 채택된 답변

dpb
dpb 2019년 3월 17일

2 개 추천

doc sortrows
% ALWAYS read "See Also" when looking for related functions!!!
>> help sort
sort Sort in ascending or descending order.
B = sort(A) sorts in ascending order.
...
See also issorted, sortrows, min, max, mink, maxk.

댓글 수: 7

matrix(:,1)=sort(matrix(:,1))
>> A = [3 6 5; 7 -2 4; 1 0 -9]
A =
3 6 5
7 -2 4
1 0 -9
>> A(:,1)=sort(A(:,1))
A =
1 6 5
3 -2 4
7 0 -9
>>
Now, while the other two columns aren't sorted, they don't match their associated data, either... :(
To do it this way, one would need something like--
[~,is]=sort(A(:,1);
A=A(is,:);
sortrows does the indexing/rearranging for you...
madhan ravi
madhan ravi 2019년 3월 17일
Completely agree dpb, as far as I understand OP just wants to sort the first column and leave the rest intact, maybe I misunderstood the question.
dpb
dpb 2019년 3월 17일
"The problem is that when I use the sort() function, it orders all my other columns too so the data is no longer associated with the correct coordinate."
madhan ravi
madhan ravi 2019년 3월 17일
편집: madhan ravi 2019년 3월 17일
+1, Yes I reread it, now its clear. Thank you dpb :), sorry for the inconvenience.
dpb
dpb 2019년 3월 17일
'S ok...we all have our moments... :) I certainly "whiff" often enough.
madhan ravi
madhan ravi 2019년 3월 18일
:)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2019년 3월 17일

댓글:

2019년 3월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by