How to arrange a matrix in descending order w.r.t rows?
12 views (last 30 days)
Show older comments
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 Comments
Answers (2)
the cyclist
on 13 Jan 2023
Edited: the cyclist
on 13 Jan 2023
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 Comments
the cyclist
on 13 Jan 2023
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
on 13 Jan 2023
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']
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!