MATLAB: Basic function to find value

allnonzerobasicfunctionscript

Hi, I have the following function which should consume a row vector and return a value of 1, if non of the elements are 0 in the vector. If an element is 0, it should return 0.
AllNonZero(a);
function AllNonZero(a)
if all(a ~= 0)
true(1)
else
false(0)
end
end
I am trying to call this function from the command window as,
AllNonZero([random_vector])
where the random_vector is any arbitrary vector. However, I get the following error,
Attempt to execute SCRIPT AllNonZero as a function:
C:\Users\fluxw\OneDrive\Documents\MATLAB\AllNonZero.m
When I run it simply as "AllNonZero" I get an output of,
AllNonZero
ans =
0×0 empty logical array
I am a beginner so any advice would be helpful. Thank you.

Best Answer

Use any() instead of all()
% Returns 0 if any elmeents are zero, 1 otherwise.
function tf = AllNonZero(vec)
tf = ~any(vec == 0)