determine all cells are non-zero within a matrix

I am trying to determine if all of the numbers in "x" is non-zero values:
x = [1 1 0]
% 1:
if x ~= [0 0 0]
disp('x is not zeros')
end
% 2:
if all(x ~= 0)
disp('x is not zeros')
end
but the output is saying the x is zeros.
what mistake did I make?

4 comentarios

Adam
Adam el 3 de Jul. de 2019
Your second version seems fine. It should return false with that example as it is not all non-zero.
Pref_Color_offset = 0.1;
if all(Pref_Color ~= 0)
disp('yes')
for i = 1:1:3
if Pref_Color(i) >= Pref_Color_offset
Pref_Color_Darkened(i) = Pref_Color(i) - Pref_Color_offset;
else
Pref_Color_Darkened(i) = Pref_Color(i);
end
if Pref_Color_Darkened(i) >= (5*Pref_Color_offset)
Pref_Color_Darkened_More(i) = Pref_Color_Darkened(i) - (5*Pref_Color_offset);
else
Pref_Color_Darkened_More(i) = Pref_Color_Darkened(i);
end
end
else
disp('no')
Pref_Color_Darkened = [0.15 0.15 0.15];
Pref_Color_Darkened_More = [1 1 1];
end
This is what I have, with a input of: Pref_Color = [1 1 0]
However, I am getting an "no" as the output.
see:
>> Pref_Color = [1 1 0];
>> Pref_Color_offset = 0.1;
if all(Pref_Color ~= 0)
disp('yes')
for i = 1:1:3
if Pref_Color(i) >= Pref_Color_offset
Pref_Color_Darkened(i) = Pref_Color(i) - Pref_Color_offset;
else
Pref_Color_Darkened(i) = Pref_Color(i);
end
if Pref_Color_Darkened(i) >= (5*Pref_Color_offset)
Pref_Color_Darkened_More(i) = Pref_Color_Darkened(i) - (5*Pref_Color_offset);
else
Pref_Color_Darkened_More(i) = Pref_Color_Darkened(i);
end
end
else
disp('no')
Pref_Color_Darkened = [0.15 0.15 0.15];
Pref_Color_Darkened_More = [1 1 1];
end
no
>>
Adam
Adam el 3 de Jul. de 2019
And why isn't this the expected answer? You are testing if all elements of Pref_Color are not equal to 0. Clearly this is false because the final element is 0 therefore it drops into your else block and reports 'no'.
Thanks for pointing out.
it should be
if ~all(Pref_Color == 0)
and now it is doing what I expected.

Iniciar sesión para comentar.

 Respuesta aceptada

Matt J
Matt J el 3 de Jul. de 2019

0 votos

Your second if statement is correct, and I get the correct output (none).

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Versión

R2016a

Etiquetas

Preguntada:

el 3 de Jul. de 2019

Comentada:

el 3 de Jul. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by