Borrar filtros
Borrar filtros

move all zeros to the right in a matrix

11 visualizaciones (últimos 30 días)
evangeline
evangeline el 14 de Feb. de 2018
Editada: Jan el 14 de Feb. de 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?

Respuestas (4)

Jan
Jan el 14 de Feb. de 2018
Editada: Jan el 14 de Feb. de 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 el 14 de Feb. de 2018
Editada: Matt J el 14 de Feb. de 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) el 14 de Feb. de 2018
Editada: Jos (10584) el 14 de Feb. de 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 el 14 de Feb. de 2018
Editada: Andrei Bobrov el 14 de Feb. de 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));

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by