フィルターのクリア

Sort a matrix in a specific format

2 ビュー (過去 30 日間)
Homayoon
Homayoon 2016 年 1 月 29 日
編集済み: Stephen23 2016 年 1 月 29 日
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.

採用された回答

Stephen23
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.

その他の回答 (1 件)

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

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by