How to find where are the location of the original values after the matrix was sorted

조회 수: 3 (최근 30일)
Hello,
I have a 6x4 matrix. I am using sort function to sort the values of each row from the smallest to the largest creating a new matrix. Is there a way to locate where each value of the first row is located in the new matrix?
THank you

채택된 답변

Stephen23
Stephen23 2019년 5월 27일
>> old = randi(9,6,4) % fake data
old =
8 6 3 6
1 4 9 4
8 1 4 8
6 3 8 7
3 8 4 1
6 8 8 5
>> [new,idx] = sort(old,2)
new =
3 6 6 8
1 4 4 9
1 4 8 8
3 6 7 8
1 3 4 8
5 6 8 8
idx =
3 2 4 1
1 2 4 3
2 3 1 4
2 1 4 3
4 1 3 2
4 1 2 3
>> [~,idy] = min(idx,[],2)
idy =
4
1
3
2
2
2
  댓글 수: 3
Stephen23
Stephen23 2019년 5월 29일
편집: Stephen23 2019년 5월 29일
"Could you specify what you do in each step mainly so I could find where the old column lies in the new matrix?"
Sure. Here is your original question and an explanation of how my code achieves this.
"I have a 6x4 matrix."
>> old = randi(9,6,4) % fake data
old =
8 6 3 6
1 4 9 4
8 1 4 8
6 3 8 7
3 8 4 1
6 8 8 5
"I am using sort function to sort the values of each row from the smallest to the largest creating a new matrix"
>> [new,idx] = sort(old,2)
new =
3 6 6 8
1 4 4 9
1 4 8 8
3 6 7 8
1 3 4 8
5 6 8 8
idx =
3 2 4 1
1 2 4 3
2 3 1 4
2 1 4 3
4 1 3 2
4 1 2 3
It is clear that each row of new is simply that of old sorted from smallest to largest, exactly as your specify in your question. The indices idx give the column position for each row r, such that new(r,:) = old(r,idx(r,:)).
"Is there a way to locate where each value of the first column [your comment] is located in the new matrix?"
Although your initially wrote "row" you amended this in a comment to "column". The first column are of course the 1's in idx, which we can trivially find using the second output of min: (because 1 is the minimum index, and we can specify min to work along the rows):
>> [~,idy] = min(idx,[],2) % 2 specifies the dimension to work along
idy =
4
1
3
2
2
2
So there you have the location of "where each value of the first column [edit] is located in the new matrix", as you requested.

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

추가 답변 (0개)

카테고리

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