How to shift all the non-zero elements of a matrix to the right of the matrix?

6 vues (au cours des 30 derniers jours)
Devika Waghela
Devika Waghela le 5 Mai 2021
Commenté : Adam Danz le 5 Mai 2021
I have a matrix like
1 2 3 0 0 1 2 0
0 0 1 2 3 0 0 0
1 0 0 1 2 3 1 2
I want to shift all the non-zero elements to the right of the matrix. The answer should be
0 0 0 1 2 3 1 2
0 0 0 0 0 1 2 3
0 0 1 1 2 3 1 2

Réponses (3)

Adam Danz
Adam Danz le 5 Mai 2021
m = [1 2 3 0 0 1 2 0
0 0 1 2 3 0 0 0
1 0 0 1 2 3 1 2];
mSort = cell2mat(cellfun(@(v){[v(v==0),v(v~=0)]},mat2cell(m,ones(size(m,1),1),size(m,2))))
mSort = 3×8
0 0 0 1 2 3 1 2 0 0 0 0 0 1 2 3 0 0 1 1 2 3 1 2

the cyclist
the cyclist le 5 Mai 2021
Modifié(e) : the cyclist le 5 Mai 2021
% The original data
M = [1 2 3 0 0 1 2 0
0 0 1 2 3 0 0 0
1 0 0 1 2 3 1 2];
% Preallocate the matrix (which also effectively fills in all the zeros)
M_sorted = zeros(size(M));
% For each row of M, identify the non-zero elements, and fill them into the
% end of each corresponding row
for nm = 1:size(M,1)
nonZeroThisRow = M(nm,M(nm,:)~=0);
M_sorted(nm,end-numel(nonZeroThisRow)+1:end) = nonZeroThisRow;
end
% Display the result
disp(M_sorted)
0 0 0 1 2 3 1 2 0 0 0 0 0 1 2 3 0 0 1 1 2 3 1 2

Sean de Wolski
Sean de Wolski le 5 Mai 2021
Modifié(e) : Sean de Wolski le 5 Mai 2021
Without loop or cells:
x = [1 2 3 0 0 1 2 0
0 0 1 2 3 0 0 0
1 0 0 1 2 3 1 2];
xt = x.';
sxr = sort(logical(xt), 1, "ascend");
[row, col] = find(sxr);
m = accumarray([col row], nonzeros(xt), size(x))
m = 3×8
0 0 0 1 2 3 1 2 0 0 0 0 0 1 2 3 0 0 1 1 2 3 1 2

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by