How to arrange a matrix in descending order w.r.t rows?
26 ビュー (過去 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!