Effacer les filtres
Effacer les filtres

move all zeros to the right in a matrix

11 vues (au cours des 30 derniers jours)
evangeline
evangeline le 14 Fév 2018
Modifié(e) : Jan le 14 Fév 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?

Réponses (4)

Jan
Jan le 14 Fév 2018
Modifié(e) : Jan le 14 Fév 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 le 14 Fév 2018
Modifié(e) : Matt J le 14 Fév 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) le 14 Fév 2018
Modifié(e) : Jos (10584) le 14 Fév 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 le 14 Fév 2018
Modifié(e) : Andrei Bobrov le 14 Fév 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));

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by