sorting values of a matrix column when the other column has the same value
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
LH
el 29 de Jul. de 2024
Comentada: Star Strider
el 29 de Jul. de 2024
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 comentarios
Respuesta aceptada
Star Strider
el 29 de Jul. de 2024
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]
.
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!