Sort two array in the same way, but only one in size order

3 Ansichten (letzte 30 Tage)
Hello!
I currently have two arrays, lets say
x =[2, 2, 1, 1 ,4 ,5]
and
y = [ 4, 5, 2 , 1, 4, 6]
and for the array x I want you use the built-in function "sort"
X = sort(x),
which gives
X = [1,1,2,2,4,5].
The problem now is that I want the same rows that changed for x should be changed for y. BUT not change the size order in y.
So, lets recall: x{:,3} = 1 and: y{:,3} = 2. So after x is sorted (x{:,3} = 1 --> X{:,1} = 1) I want y{:,3} = 2 --> Y{:,1} = 2. That is, the same rows changed for both.
To make it a bit more clear, what I want after the operation is the following:
x =[2, 2, 1, 1 ,4 ,5] %start array
y = [ 4, 5, 2 , 1, 4] % start array
X = sort(x) %the new sorted array for x
Y = ....... something
X = [1,1,2,2,4,5] % sorted array
Y = [2,1,4,5,4,6] %sorted after X.
now
Now the same rows were changed in both arrays. That is, the same rows were changed for both, but only the first was changed in size order.
I hope I made some sense trying to explain the problem. Let me know if there is any confusion.
Thanks
G

Akzeptierte Antwort

Stephen23
Stephen23 am 8 Mär. 2023
Bearbeitet: Stephen23 am 8 Mär. 2023
"The problem now is that I want the same rows that changed for x should be changed for y. "
It is not a problem, because when you read the SORT documentation you see that SORT has a 2nd output argument which are the sort indices (this is why reading the documentation is highly recommended):
x = [2,2,1,1,4,5];
y = [4,5,2,1,4,6];
[xNew,idx] = sort(x);
yNew = y(idx)
yNew = 1×6
2 1 4 5 4 6
xNew
xNew = 1×6
1 1 2 2 4 5
Using indexing is a MATLAB super-power, which is explained in the introductory tutorials:

Weitere Antworten (0)

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by