move all zeros to the right in a matrix

7 views (last 30 days)
evangeline
evangeline on 14 Feb 2018
Edited: Jan on 14 Feb 2018
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?

Answers (4)

Jan
Jan on 14 Feb 2018
Edited: Jan on 14 Feb 2018
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 on 14 Feb 2018
Edited: Matt J on 14 Feb 2018
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) on 14 Feb 2018
Edited: Jos (10584) on 14 Feb 2018
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 on 14 Feb 2018
Edited: Andrei Bobrov on 14 Feb 2018
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));

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!