function nbDeZero = EstMatriceCreuse(matrice)
matrice = [1,2,3,0,0,0,0,0;1,2,3,4,5,0,0,0];
validateattributes(matrice,{'double'},{'2d','nonempty'})
[m,n] = size(matrice);
o = 0 ;
for i = 1 : m
for j = 1 : n
if matrice(m,n) == 0
o = o + 1;
end
end
end
fprintf('%d',o);
end
For some reason my variable o increments everytime...even if the number is not zero. I'm kinda of a newbie so I don't know what is the problem. please help.

 Respuesta aceptada

Jan
Jan el 8 de Mzo. de 2022
Editada: Jan el 10 de Mzo. de 2022

1 voto

Replace
if matrice(m,n) == 0
by
if matrice(i,j) == 0
Currently you are checking the last element of the matrix in each iteration.
A standard method to examine such problems is to add some output of the currently processed element to the command window.
By the way, the singular of "matrices" is "matrix".
Some matlabish way to count the zero elements: [EDITED, thanks Image Analyst!]
sum(A(:) == 0)
numel(A) - nnz(A)

5 comentarios

DGM
DGM el 8 de Mzo. de 2022
matrice creuse : sparse matrix
... not that I'm any authority on other languages. That's just what I get when I point my translator plugin at it.
Image Analyst
Image Analyst el 9 de Mzo. de 2022
For the second one, I assume you meant
numNonZeros = nnz(A)
Jan
Jan el 9 de Mzo. de 2022
@Image Analyst: The OP counts the number of zeros, so numel(A)-nnz(A) is correct. Or nnz(~A) .
Image Analyst
Image Analyst el 9 de Mzo. de 2022
OK, but at the end of your comment you said:
"Some matlabish way to count the non-zero elements:"
sum(A(:) == 0)
numel(A) - nnz(A)
"nnz(A)" is the number of non-zeros, not "numel(A)-nnz(A)"
That's what I was referring to.
I guess you really meant "Some matlabish way to count the zero elements:"
Jan
Jan el 10 de Mzo. de 2022
Ah, yes. Thanks. I've fixed it.

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 9 de Mzo. de 2022

0 votos

Get rid of this line
matrice = [1,2,3,0,0,0,0,0;1,2,3,4,5,0,0,0];
because it just blows away any matrix you pass in via the argument list.
Also you're using the wrong indexes in
if matrice(m,n) == 0
That just looks at the very last element in the lower right corner of the matrix.
It should be
if matrice(j, i) == 0
Plus you're never assigning nbDeZero. You need to do
nbDeZero = o;
at the end of the function. Also don't use o as the variable name because it looks too much like 0. Use numNonZeros or some other descriptive variable name.

Categorías

Más información sobre Linear Algebra en Centro de ayuda y File Exchange.

Productos

Versión

R2021b

Etiquetas

Preguntada:

el 8 de Mzo. de 2022

Comentada:

Jan
el 10 de Mzo. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by