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

조회 수: 5 (최근 30일)
Gustav Lönnblad
Gustav Lönnblad 2023년 3월 8일
댓글: Gustav Lönnblad 2023년 3월 8일
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

채택된 답변

Stephen23
Stephen23 2023년 3월 8일
편집: Stephen23 2023년 3월 8일
"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:

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by