How to shift all the non-zero elements of a matrix to the right of the matrix?

8 ビュー (過去 30 日間)
Devika Waghela
Devika Waghela 2021 年 5 月 5 日
コメント済み: Adam Danz 2021 年 5 月 5 日
I have a matrix like
1 2 3 0 0 1 2 0
0 0 1 2 3 0 0 0
1 0 0 1 2 3 1 2
I want to shift all the non-zero elements to the right of the matrix. The answer should be
0 0 0 1 2 3 1 2
0 0 0 0 0 1 2 3
0 0 1 1 2 3 1 2

回答 (3 件)

Adam Danz
Adam Danz 2021 年 5 月 5 日
m = [1 2 3 0 0 1 2 0
0 0 1 2 3 0 0 0
1 0 0 1 2 3 1 2];
mSort = cell2mat(cellfun(@(v){[v(v==0),v(v~=0)]},mat2cell(m,ones(size(m,1),1),size(m,2))))
mSort = 3×8
0 0 0 1 2 3 1 2 0 0 0 0 0 1 2 3 0 0 1 1 2 3 1 2

the cyclist
the cyclist 2021 年 5 月 5 日
編集済み: the cyclist 2021 年 5 月 5 日
% The original data
M = [1 2 3 0 0 1 2 0
0 0 1 2 3 0 0 0
1 0 0 1 2 3 1 2];
% Preallocate the matrix (which also effectively fills in all the zeros)
M_sorted = zeros(size(M));
% For each row of M, identify the non-zero elements, and fill them into the
% end of each corresponding row
for nm = 1:size(M,1)
nonZeroThisRow = M(nm,M(nm,:)~=0);
M_sorted(nm,end-numel(nonZeroThisRow)+1:end) = nonZeroThisRow;
end
% Display the result
disp(M_sorted)
0 0 0 1 2 3 1 2 0 0 0 0 0 1 2 3 0 0 1 1 2 3 1 2

Sean de Wolski
Sean de Wolski 2021 年 5 月 5 日
編集済み: Sean de Wolski 2021 年 5 月 5 日
Without loop or cells:
x = [1 2 3 0 0 1 2 0
0 0 1 2 3 0 0 0
1 0 0 1 2 3 1 2];
xt = x.';
sxr = sort(logical(xt), 1, "ascend");
[row, col] = find(sxr);
m = accumarray([col row], nonzeros(xt), size(x))
m = 3×8
0 0 0 1 2 3 1 2 0 0 0 0 0 1 2 3 0 0 1 1 2 3 1 2

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by