of the first collumn
How to find where are the location of the original values after the matrix was sorted
1 回表示 (過去 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
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
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 Center および File Exchange で Shifting and Sorting Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!