How to arrange a matrix in descending order w.r.t rows?
조회 수: 13 (최근 30일)
이전 댓글 표시
If we have a large matrix and we want to arrange it in descending order i.e., the largest row shoud come on top, then 2nd largest row comes as 2nd row, then 3rd largest as 3rd row and so on but the columns are not disturbed. I do it like this:
clear all; clc
a=[1 2 3 4;1.1 2.1 3.1 4.1;1.2 0 3.2 4.2];
b=sort(a,"descend");
[a b]
But in this the columns are also disturbed.
댓글 수: 0
답변 (2개)
the cyclist
2023년 1월 13일
편집: the cyclist
2023년 1월 13일
Probably use the sortrows function. I'd be more specific, but it is unclear to me what you mean by "largest row". For example, which row is larger?
M = [2 7 11 19;
3 5 13 17];
댓글 수: 3
the cyclist
2023년 1월 13일
I'm not sure I understand. I ran your code here (and wrote a in a way that makes the rows clearer).
Each row stays intact, but is moved up or down, based on the sorting you did. This isn't what you want? Maybe you could write out the output you expected to get?
fval=[2.11 2.10 2.13 2.18 2.09];
a=[1 2 3 4;
1.1 2.1 3.1 4.1;
1.2 0 3.2 4.2;
1.01 2.01 3.01 4.01;
1.1 2.9 3.1 4.2];
[fval1 ind]=sort(fval,'descend');
b=a(ind,:)
the cyclist
2023년 1월 13일
Answering here, based on your comment to my other answer.
It seems that you just want to sort the matrix a according to its norm. It also seems that the vector fval has absolutely nothing to do with the norm. So why are you sorting by fval?
This code will create the matrix b, which it seems is what you want.
% Original matrix
a = [1 2 3 4;
1.1 2.1 3.1 4.1;
1.2 0 3.2 4.2;
1.01 2.01 3.01 4.01;
1.1 2.9 3.1 4.2];
% Calculate the norm of each row of a
for ii = 1:height(a)
Na(ii) = norm(a(ii,:));
end
% Find the sorting order index
[~, ind]=sort(Na,'descend');
% Define the matrix b, which is a sorted by the norm
b = a(ind,:);
% Calculate the norm of each row of b
for ii = 1:height(a)
Nb(ii) = norm(b(ii,:));
end
% Show that b is sorted by the norm
Both = [Na' Nb']
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!