Sort a matrix in a specific format
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Homayoon
am 29 Jan. 2016
Bearbeitet: Stephen23
am 29 Jan. 2016
Hello All,
I have an interesting question which could be very helpful for my research. I have matrix which is 2*5 and I want to sort the elements in the ascending way based on the first row of the matrix. Assume the matrix A as the following:
A = [ 4, 0, 0, 1, 2
11, 0, 0, 20, 1]
Well the code for this purpose is simply:
X = sortrows(A',1)'
which gives me the following output:
X = [0, 0, 1, 2, 4
0, 0, 20, 1, 11]
However, for my convenience, I'd like to sort the matrix A such that the output will be look a like
X = [1, 2, 4, 0, 0
20, 1, 11, 0, 0]
in other words I still want to sort the matrix A in an ascending format based on the first row but without considering zero elements i.e. I want the zero elements go to the very right side of the output and then sort the numbers of the first row in an ascending way.
Thank you so much for your help.
0 Kommentare
Akzeptierte Antwort
Stephen23
am 29 Jan. 2016
Bearbeitet: Stephen23
am 29 Jan. 2016
>> A = [ 4, 0, 0, 1, 2; 11, 0, 0, 20, 1]
A =
4 0 0 1 2
11 0 0 20 1
>> X = all(A==0,1);
>> [sortrows(A(:,~X).',1).',A(:,X)]
ans =
1 2 4 0 0
20 1 11 0 0
Note that it is a good habit to use transpose .' instead of complex conjugate transpose '. Unless you need the complex conjugate, of course.
0 Kommentare
Weitere Antworten (1)
Geoff Hayes
am 29 Jan. 2016
Homayoon - will it always be true that you will only have columns of zeros that need to be "pushed" to the end of the matrix? And is it always true that you will have positive elements? If yes to both, then you could try the following
X = sortrows(A',1)';
nzIdx = find(X(1,:)>0,1); % find the first element in the first row that is non-zero
if ~isempty(nzIdx) && nzIdx>1
X = [X(:,idx:end) X(:,1:idx-1)]; % "push" the columns of zeros to the end
end
(There may be more efficient algorithms than the above.)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!