I am trying to find the number of nonzero elements I have in a matrix without using the nnz function.

3 Ansichten (letzte 30 Tage)
Is there a way I can use sums or another function to add up the number of nonzero elements in a matrix. I know of the nnz function but I am not allowed to use it on the project I am working on because we haven't learned it in class.
Thank you for your help!

Akzeptierte Antwort

Roger Stafford
Roger Stafford am 27 Apr. 2017
If M is your matrix do this:
s = sum(M(:)~=0);

Weitere Antworten (1)

MH Rahat
MH Rahat am 13 Feb. 2022
simply use, s= nnz(M)

Kategorien

Mehr zu Sparse Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by