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

조회 수: 3 (최근 30일)
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!

채택된 답변

Roger Stafford
Roger Stafford 2017년 4월 27일
If M is your matrix do this:
s = sum(M(:)~=0);

추가 답변 (1개)

MH Rahat
MH Rahat 2022년 2월 13일
simply use, s= nnz(M)

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by