# sort the matrix by the order of the first row

7 views (last 30 days)
Berfin Çetinkaya on 19 May 2022
Commented: Jadyn on 8 Nov 2022
i have a matrix.I want to sort the columns of this matrix to be 1,2,3,4,5.... (note: my real matrix is very big. I gave these matrices as an example)
for example
3 5 4 1 2
0.2 0.5 0.7 0.1 0.9
0.7 0.9 0.4 0.3 0.2
new matrix :
1 2 3 4 5
0.1 0.9 0.2 0.7 0.5
0.3 0.2 0.7 0.4 0.9
can you help me with this?
Thanks, Berfin

Voss on 19 May 2022
A = [ ...
3 5 4 1 2
0.2 0.5 0.7 0.1 0.9
0.7 0.9 0.4 0.3 0.2];
[~,idx] = sort(A(1,:));
B = A(:,idx)
B = 3×5
1.0000 2.0000 3.0000 4.0000 5.0000 0.1000 0.9000 0.2000 0.7000 0.5000 0.3000 0.2000 0.7000 0.4000 0.9000
Hi! This is so helpful--thanks so much! I had a similar question: what if you had a missing column, and you want to skip the missing column?
For example, original matrix:
A = [
5 4 1 2
0.5 0.7 0.1 0.9
0.9 0.4 0.3 0.2];
I want my new matrix to look like this:
1.0000 2.0000 0.0000 4.0000 5.0000
0.1000 0.9000 0.0000 0.7000 0.5000
0.3000 0.2000 0.0000 0.4000 0.9000
(doesn't have to be zeros as long as the column is empty)