find sum of all the entries with value 0

I have a cell matrix of mat = [ 1 0 0 4;0 2 0 4], i want to find the sum of the all the entries having value 0. in the case of given example the entries having count 0 are 4; so sum will be 4. how can i do this.

 Respuesta aceptada

Matt J
Matt J el 29 de Nov. de 2013
Editada: Matt J el 29 de Nov. de 2013
sum(~mat(:))

3 comentarios

arun
arun el 29 de Nov. de 2013
sum(sum(~mat))
Thank You.
Matt J
Matt J el 29 de Nov. de 2013
Editada: Matt J el 29 de Nov. de 2013
No, what I proposed
sum(~mat(:))
works indepedently of ndims(mat) and will save you additional function calls to sum().
arun
arun el 30 de Nov. de 2013
okieee,sorry............... i got it.

Iniciar sesión para comentar.

Más respuestas (1)

Jos (10584)
Jos (10584) el 30 de Nov. de 2013
NNZ is the dedicated function to do this:
nnz(~mat)

3 comentarios

NNZ is optimal for sparse matrices. For full, sum is faster,
A=sprand(1e4,1e4,1e-3)>0;
Af=full(A);
tic;nnz(A);toc
%Elapsed time is 0.000031 seconds.
tic;sum(A(:));toc
%Elapsed time is 0.000491 seconds.
tic;nnz(Af);toc
Elapsed time is 0.083754 seconds.
tic;sum(Af(:));toc
Elapsed time is 0.053861 seconds.
John D'Errico
John D'Errico el 30 de Nov. de 2013
Note that nnz(~mat) will be poor even for large sparse matrices, because if mat is sparse, then ~mat must create a large and rather dense logical matrix. Better then would be to use a form like:
numel(mat) - nnz(mat)
In my tests, for a large fairly sparse matrix like that generated by Matt in his comment, my form was the fastest.
Jos (10584)
Jos (10584) el 2 de Dic. de 2013
Thanks, Matt and John, for the insights.

Iniciar sesión para comentar.

Categorías

Más información sobre Sparse Matrices en Centro de ayuda y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Preguntada:

el 29 de Nov. de 2013

Comentada:

el 2 de Dic. de 2013

Community Treasure Hunt

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

Start Hunting!

Translated by