Number of zeros in a matrix

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.

2 Kommentare

Azzi Abdelmalek
Azzi Abdelmalek am 17 Nov. 2012
Why did you need to do it with if condition?
Bob Choy
Bob Choy am 17 Nov. 2012
Because thats what I usually work with but if thats impossible nevermind it.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Matt Fig
Matt Fig am 17 Nov. 2012
Bearbeitet: Matt Fig am 17 Nov. 2012

0 Stimmen

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)

5 Kommentare

Bob Choy
Bob Choy am 18 Nov. 2012
It works, awesome! Now to the hard part, how do I find out which columns have more than 12 zeros and then write that info into a .txt file?
Thank you.
Matt Fig
Matt Fig am 18 Nov. 2012
What do you mean by write to a text file? You want to write only those columns that do or do not have more than 12 zeros? You want to write the whole column including all the zeros?
Bob Choy
Bob Choy am 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.
Matt Fig
Matt Fig am 18 Nov. 2012
M = [1 0 1 1;1 1 1 0]
fid = fopen('mytext.txt','wt')
fprintf(fid,'%i ',find(sum(~M) >= 1))
fclose(fid)
Bob Choy
Bob Choy am 18 Nov. 2012
Thank you so much! Keep up the good work, cheers!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Andrei Bobrov
Andrei Bobrov am 17 Nov. 2012

1 Stimme

a - your matrix
number_columns = find(sum(~a) > 12);

Kategorien

Mehr zu Data Type Identification finden Sie in Hilfe-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