# sort the matrix by the order of the first row

5 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
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Accepted Answer

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
##### 5 CommentsShow 3 older commentsHide 3 older comments
Voss on 19 May 2022
A = [ ...
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];
B = [3 5 4 1 2];
[~,idx] = ismember(B,A(1,:));
C = A(:,idx)
C = 3×5
3.0000 5.0000 4.0000 1.0000 2.0000 0.2000 0.5000 0.7000 0.1000 0.9000 0.7000 0.9000 0.4000 0.3000 0.2000
Jadyn on 8 Nov 2022
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)

Sign in to comment.

### 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!