Sort a matrix in a specific format
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2016-1-29
编辑:Stephen23
2016-1-29
>> 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 个评论
更多回答(1 个)
Geoff Hayes
2016-1-29
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!