필터 지우기
필터 지우기

Reordering columns based on first row?

조회 수: 1 (최근 30일)
Jadyn
Jadyn 2022년 11월 8일
댓글: Voss 2022년 11월 9일
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!!
Voss
Voss 2022년 11월 9일
You're welcome!

댓글을 달려면 로그인하십시오.

추가 답변 (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