Filter löschen
Filter löschen

move all zeros to the right in a matrix

11 Ansichten (letzte 30 Tage)
evangeline
evangeline am 14 Feb. 2018
Bearbeitet: Jan am 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?

Antworten (4)

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

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by