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:
  1 件のコメント
Gustav Lönnblad
Gustav Lönnblad 2023 年 3 月 8 日
Okay, good to know.
Thank you very much!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting 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