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

조회 수: 7 (최근 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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by