Filter löschen
Filter löschen

Reordering columns based on first row?

1 Ansicht (letzte 30 Tage)
Jadyn
Jadyn am 8 Nov. 2022
Kommentiert: Voss am 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!

Akzeptierte Antwort

Voss
Voss am 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 Kommentare
Jadyn
Jadyn am 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 am 9 Nov. 2022
You're welcome!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by