# How to Sort Matrix Rows from Highest to Lowest

조회 수: 5 (최근 30일)
Brian 2024년 7월 30일
댓글: Stephen23 2024년 7월 31일
Simplied my problem so it's easier to solve. Let's pretend I have MatrixA that has 2 columns, and I want to sort the rows from highest to lowest depending on the value of the cell in the second column. How would I do this?
I also have a VectorB that starts at 10 and would like to add the value of each row in column 2 of the sorted MatrixA. How would I do this? Note this needs to come after MatrixA is sorted from highest to lowest.
Any suggestions matlab wizards out there? Really want to avoid using loops to make the code inefficient.
%Just creating example of the matrix I want to sort you can ignore this
MatrixA = cell(3,2);
MatrixA{1,1} = "D1";
MatrixA{2,1} = "D2";
MatrixA{3,1} = "D3";
MatrixA{1,2} = 5;
MatrixA{2,2} = 15;
MatrixA{3,2} = 10;
% Creating Vector B based on the already defined values for MatrixA which aren't in order
VectorA = [10 10+MatrixA{1,2} 10+MatrixA{2,2} 10+MatrixA{3,2}];
% How would I sort MatrixA from highest to lowest here and the values of VectorB to be based on the sorted MatrixA?
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Stephen23 2024년 7월 31일
"How would I do this?"
By using a table, which would suit your data better.

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

### 답변 (2개)

Walter Roberson 2024년 7월 30일
MatrixA = cell(3,2);
MatrixA{1,1} = "D1";
MatrixA{2,1} = "D2";
MatrixA{3,1} = "D3";
MatrixA{1,2} = 5;
MatrixA{2,2} = 15;
MatrixA{3,2} = 10;
T = cell2table(MatrixA)
T = 3x2 table
MatrixA1 MatrixA2 ________ ________ "D1" 5 "D2" 15 "D3" 10
sortrows(T, 2, 'descend')
ans = 3x2 table
MatrixA1 MatrixA2 ________ ________ "D2" 15 "D3" 10 "D1" 5
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

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

dpb 2024년 7월 30일
편집: dpb 2024년 7월 31일
It's not clear about B, but
A = cell(3,2);
A(:,1)=cellstr("D"+[1:3]);
A(:,2)={5;15;10};
A=sortrows(A,2,'descend')
A = 3x2 cell array
{'D2'} {[15]} {'D3'} {[10]} {'D1'} {[ 5]}
B=10+[A{:,2}].'
B = 3x1
25 20 15
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
if I interpret the intent for B corrrectly.

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

### 카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by