Sort a matrix in a specific format

1 view (last 30 days)
Homayoon
Homayoon on 29 Jan 2016
Edited: Stephen23 on 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.

Accepted Answer

Stephen23
Stephen23 on 29 Jan 2016
Edited: Stephen23 on 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.

More Answers (1)

Geoff Hayes
Geoff Hayes on 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.)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!