Reordering columns based on first row?

1 次查看(过去 30 天)
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!

采纳的回答

Voss
Voss 2022-11-8
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 个评论
Jadyn
Jadyn 2022-11-9
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!!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by