sort the matrix by the order of the first row

4 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Voss
Voss il 19 Mag 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 Commenti
Voss
Voss il 19 Mag 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
Jadyn il 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)

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by