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

4 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Stephen23
Stephen23 el 8 de Mzo. de 2023
Editada: Stephen23 el 8 de Mzo. de 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:

Más respuestas (0)

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by