Asked by Bob Choy
on 17 Nov 2012

I need to create a function where I have a matrix and the function returns the number of zeros in that matrix. I need to do this using the if condition.

Then write in a .txt file which columns had more than 12 zeros.

Can someone help me out with this?

Thank you very much.

*No products are associated with this question.*

Answer by Loginatorist
on 17 Nov 2012

Edited by Loginatorist
on 17 Nov 2012

Accepted Answer

The number of zeros in the matrix A is:

sum(~A(:))

So we can make this a function:

f = @(x) sum(~x(:));

Now test it:

x = [1 2 3;0 0 0;3 0 9] f(x)

Bob Choy
on 18 Nov 2012

I want to write in a .txt file numbers of the columns that have more than 12 zeros. E.g. say I wanted the columns with atleast one zero. (Ignore the "if true" nonsense]

if true % code end M = 1 0 1 1 1 1 1 0

I want the function to save a .txt file with the numbers 2 and 4.

Loginatorist
on 18 Nov 2012

Bob Choy
on 18 Nov 2012

Thank you so much! Keep up the good work, cheers!

Log in to comment.

Answer by Andrei Bobrov
on 17 Nov 2012

a - your matrix

number_columns = find(sum(~a) > 12);

Log in to comment.

Related Content

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
## 2 Comments

## Azzi Abdelmalek (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/54006-number-of-zeros-in-a-matrix#comment_111706

Why did you need to do it with if condition?

## Bob Choy (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/54006-number-of-zeros-in-a-matrix#comment_111709

Because thats what I usually work with but if thats impossible nevermind it.

Log in to comment.