MATLAB Answers

How to remove zeros from an array?

4,972 views (last 30 days)
Elvis Somers
Elvis Somers on 20 Mar 2017
Commented: Farshad Bolouri on 8 Nov 2020 at 23:33
I want to remove zeroes from an array. The array has exactly one zero per row. For example:
a = [1 4 0 3; 0 1 5 5; 1 0 8 1; 5 4 4 0; 0 1 5 2]
Should be turned into
a = [1 4 3; 1 5 5; 1 8 1; 5 4 4; 1 5 2]
I have tried using the command
a(a==0) = [];
However, this turns the 2000x50 array into an 1x98000 array instead of an 2000x49 array like I want it. Any ideas?

  0 Comments

Sign in to comment.

Accepted Answer

Beder
Beder on 20 Mar 2017
Edited: MathWorks Support Team on 28 Nov 2018
To remove a single zero from each row of a matrix and rebuild the new matrix of nonzero entries, try the following code:
a = [1 4 0 3; 0 1 5 5; 1 0 8 1; 5 4 4 0; 0 1 5 2]
v = nonzeros(a');
newmat = reshape(v,3,5)'

More Answers (1)

saber kazemi
saber kazemi on 12 Dec 2018
If we do not know how much of the elements to submit after we remove the zero elements.
a = [is a big matrix]
v = nonzeros(a');
newmat = reshape(v,?,?)'
Any ideas?

  2 Comments

ytzhak goussha
ytzhak goussha on 16 Dec 2018
I have been working on this problme for the some time now,
so far the solution that i have reached works better if you know for certain that the number of zeros in each row is the same, if not, then it must be converted to a cell class.
a=matrix %a big matrix with unknown number of zeroes
[sz1,sz2]=size(a);
new_sz2=zeros(1,sz1) %This array will hold the size of each row after removing zeros
for i=1:sz1
new_mat{i}= nonzeros(a(i,:));
new_row_sz(i)=size(new_mat{i},1)
end
if range(new_row_sz) == 0
new_mat=cell2mat(new_mat);
end
Farshad Bolouri
Farshad Bolouri on 8 Nov 2020 at 23:33
This is how I have solved this problem:
Z = find(~a);
[x,~] = ind2sub(size(a),Z);
a(x,:) = [];
This worked for my application. Please me know if it also works for you. It is possible to tweek it for different applications.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!