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

1 view (last 30 days)
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.

Accepted Answer

Star Strider
Star Strider on 29 Jul 2024
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>
.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!