Clear Filters
Clear Filters

Reordering columns based on first row?

1 view (last 30 days)
Jadyn
Jadyn on 8 Nov 2022
Commented: Voss on 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!

Accepted Answer

Voss
Voss on 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 Comments
Jadyn
Jadyn on 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!!

Sign in to comment.

More Answers (0)

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!