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

5 vues (au cours des 30 derniers jours)
Gustav Lönnblad
Gustav Lönnblad le 8 Mar 2023
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

Réponse acceptée

Stephen23
Stephen23 le 8 Mar 2023
Modifié(e) : Stephen23 le 8 Mar 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:

Plus de réponses (0)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by