Azzera filtri
Azzera filtri

Reordering columns based on first row?

1 visualizzazione (ultimi 30 giorni)
Jadyn
Jadyn il 8 Nov 2022
Commentato: Voss il 9 Nov 2022
Commented on this post, but posting as a question here.
Suppose I have a matrix:
A = [
5 4 1 2
0.5 0.7 0.1 0.9
0.9 0.4 0.3 0.2];
I'd like to use my first row as an index, so that my matrix is organized in an ascending order.
I know I can use sort:
[~,idx] = sort(A(1,:));
B = A(:,idx)
but this would give me a 3 by 4 matrix. I'd like a 3 by 5 matrix, such that the output looks 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)
I'd appreciate any help with this--thanks so much in advance!

Risposta accettata

Voss
Voss il 8 Nov 2022
Using the elements of the first row of A as column indices in B:
A = [
5 4 1 2
0.5 0.7 0.1 0.9
0.9 0.4 0.3 0.2];
B = zeros(size(A,1),max(A(1,:)));
B(:,A(1,:)) = A
B = 3×5
1.0000 2.0000 0 4.0000 5.0000 0.1000 0.9000 0 0.7000 0.5000 0.3000 0.2000 0 0.4000 0.9000
  2 Commenti
Jadyn
Jadyn il 9 Nov 2022
I don't know why I can't accept/upvote your answer but this is exactly what I was looking for--thank you so much!!
Voss
Voss il 9 Nov 2022
You're welcome!

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