sorting values of a matrix column when the other column has the same value

1 回表示 (過去 30 日間)
LH
LH 2024 年 7 月 29 日
コメント済み: Star Strider 2024 年 7 月 29 日
Hi all,
I have a matrix Athat has two columns as following:
A = [0.1 0.1 ; 0.1 -0.3 ; 0.1 0.5 ; 0.1 0; 0.1 -0.5; 0.1 -0.1; 0.1 0.4;
0.2 0.1 ; 0.2 -0.3 ; 0.2 0.5 ; 0.2 0; 0.2 -0.5; 0.2 -0.1; 0.2 0.4;
0.3 0.1 ; 0.3 -0.3 ; 0.3 0.5 ; 0.3 0; 0.3 -0.5; 0.3 -0.1; 0.3 0.4];
And I want to sort the second column of this matrix for every uniqe value of the first column so that the result looks like:
Asorted = [0.1 -0.5 ; 0.1 -0.3 ; 0.1 -0.1 ; 0.1 0; 0.1 0.1; 0.1 0.4; 0.1 0.5;
0.2 -0.5 ; 0.2 -0.3 ; 0.2 -0.1 ; 0.2 0; 0.2 0.1; 0.2 0.4; 0.2 0.5;
0.3 -0.5 ; 0.3 -0.3 ; 0.3 -0.1 ; 0.3 0; 0.3 0.1; 0.3 0.4; 0.3 0.5];
My "failing" attempt of doing this is the following:
A1 = A(:,1); %forst column
A2 = A(:,2); %second column
Auni = unique(A1); %unique value of the first column
for i = 1:size(A,1) %go through all the points in the first column
for j = 1:numel(Auni) %go throguh the unique values of the first column
if A1(i) == Auni(j) %if the point equals one of the uniqe values
[A2 , sortdx] = sort(A2); %sort out the second column of matrix A
A1 = A1(sortidx); %sort the first column accordingly
Asorted = [A1 A2]; %combine both results.
end
end
end
Also, how can I reorder another matrix B based on the sorting done previously on matrix A?
Any help would be appreicted.
Thanks.

採用された回答

Star Strider
Star Strider 2024 年 7 月 29 日
Use the sortrows function, sorting the first column then the second column —
A = [0.1 0.1 ; 0.1 -0.3 ; 0.1 0.5 ; 0.1 0; 0.1 -0.5; 0.1 -0.1; 0.1 0.4;
0.2 0.1 ; 0.2 -0.3 ; 0.2 0.5 ; 0.2 0; 0.2 -0.5; 0.2 -0.1; 0.2 0.4;
0.3 0.1 ; 0.3 -0.3 ; 0.3 0.5 ; 0.3 0; 0.3 -0.5; 0.3 -0.1; 0.3 0.4];
Asorted = sortrows(A, [1 2])
Asorted = 21x2
0.1000 -0.5000 0.1000 -0.3000 0.1000 -0.1000 0.1000 0 0.1000 0.1000 0.1000 0.4000 0.1000 0.5000 0.2000 -0.5000 0.2000 -0.3000 0.2000 -0.1000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Asorted = [0.1 -0.5 ; 0.1 -0.3 ; 0.1 -0.1 ; 0.1 0; 0.1 0.1; 0.1 0.4; 0.1 0.5;
0.2 -0.5 ; 0.2 -0.3 ; 0.2 -0.1 ; 0.2 0; 0.2 0.1; 0.2 0.4; 0.2 0.5;
0.3 -0.5 ; 0.3 -0.3 ; 0.3 -0.1 ; 0.3 0; 0.3 0.1; 0.3 0.4; 0.3 0.5]
Asorted = 21x2
0.1000 -0.5000 0.1000 -0.3000 0.1000 -0.1000 0.1000 0 0.1000 0.1000 0.1000 0.4000 0.1000 0.5000 0.2000 -0.5000 0.2000 -0.3000 0.2000 -0.1000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
.
  2 件のコメント
LH
LH 2024 年 7 月 29 日
Many thanks!
Star Strider
Star Strider 2024 年 7 月 29 日
As always, my pleasure!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by