sorting values of a matrix column when the other column has the same value
1 回表示 (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
採用された回答
Star Strider
2024 年 7 月 29 日
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 = [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]
.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Shifting and Sorting Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!