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

7 次查看(过去 30 天)
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