move all zeros to the right in a matrix

4 次查看(过去 30 天)
I have a matrix like
[1,2,3,0;
0,0,0,1;
8,0,9,0;
4,3,2,1]
and I need to move all zeros to the right, and other numbers to the left. like:
[1,2,3,0;
1,0,0,0;
8,9,0,0;
4,3,2,1]
how can I do this?

回答(4 个)

Jan
Jan 2018-2-14
编辑:Jan 2018-2-14
X = [1,2,3,0; 0,0,0,1; 8,0,9,0; 4,3,2,1];
[c, r] = size(X);
[~, S] = sort(X == 0, 2);
Index = sub2ind(size(X), repmat((1:c).', 1, r), S);
Y = X(Index)
Or replace sub2in by a simpler method:
c = size(X, 1);
[~, S] = sort(X == 0, 2);
Y = X((1:c).' + (S - 1) * c) % >= R2016b: Auto-expanding
With older Matlab versions:
Y = X(bsxfun(@plus, (1:c).', (S - 1) * c)

Matt J
Matt J 2018-2-14
编辑:Matt J 2018-2-14
A=[1,2,3,0;0,0,0,1;8,0,9,0;4,3,2,1]
[m,n]=size(A);
for i=1:m,
tmp=nonzeros(A(i,:));
A(i,:)=[tmp.', zeros(1,n-numel(tmp))];
end
A,

Jos (10584)
Jos (10584) 2018-2-14
编辑:Jos (10584) 2018-2-14
Here is one way:
% data
X = [1 2 3 0 4 ; 1 0 0 0 2 ; 1 0 2 3 4 ; 1 2 3 0 0 ; 0 0 0 0 1]
% engine
X = X.'
Y = zeros(size(X))
Q = logical(X)
Qs = sort(Q,1,'descend')
Y(Qs) = X(Q)
Y = Y.'

Andrei Bobrov
Andrei Bobrov 2018-2-14
编辑:Andrei Bobrov 2018-2-14
a = [1,2,3,0;
0,0,0,1;
8,0,9,0;
4,3,2,1];
b = a';
out = sort(b,'descend')
out(out>0) = b(b>0);
out = out';
or
a = [1,2,3,0;
0,0,0,1;
8,0,9,0;
4,3,2,1];
lo = a ~= 0;
[ii,~,k] = find(cumsum(lo,2).*lo);
out = accumarray([ii,k],a(lo));

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by