how to sort the element of one column in a 220*3 matrix in ascending mode, keeping the elements of other columns dependent on the elements of sorted column ?

조회 수: 2 (최근 30일)
i have a 220*3 matrix. the elements of first column in this matrix is related to the elements of other 2 columns. how can i sort the elements of first column in ascending mode, moving the elements of other columns correlated to the elements of first column?

채택된 답변

Stephen23
Stephen23 2015년 7월 20일
편집: Stephen23 2015년 7월 20일
If you want to move the entire row based on how the first column is sorted, then use sortrows with its second optional argument (the rows move along with the first column):
sortrows(X,1)
For example:
>> X = [9,1,1,1;1,2,2,2;5,3,3,3]
X =
9 1 1 1
1 2 2 2
5 3 3 3
>> sortrows(X,1)
ans =
1 2 2 2
5 3 3 3
9 1 1 1
If you want to sort only the first column then just use sort and the appropriate indexing (the other columns do not change):
X(:,1) = sort(X(:,1));
  댓글 수: 2
Joseph
Joseph 2015년 7월 20일
and what if a few elements of first column are the same and i decide to sort with the descending elements of third column?
Stephen23
Stephen23 2015년 7월 20일
편집: Stephen23 2015년 7월 20일
If you had actually read the link to the sortrows documentation that I gave you, then you would already know how: use the second optional argument to do exactly what you want:
sortrows(X,[1,-3])

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

추가 답변 (1개)

Jan
Jan 2015년 7월 20일
And this happens inside sortrows:
X = rand(220, 3);
[Y, Order] = sort(X(:, 1));
R = X(Order, :);

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by