of the first collumn
How to find where are the location of the original values after the matrix was sorted
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Georgios Tertikas
am 27 Mai 2019
Kommentiert: Georgios Tertikas
am 30 Mai 2019
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
Akzeptierte Antwort
Stephen23
am 27 Mai 2019
>> 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 Kommentare
Stephen23
am 29 Mai 2019
Bearbeitet: Stephen23
am 29 Mai 2019
"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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!