Basic function to find value
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Image Analyst
2019-3-18
Use any() instead of all()
% Returns 0 if any elmeents are zero, 1 otherwise.
function tf = AllNonZero(vec)
tf = ~any(vec == 0)
0 个评论
更多回答(1 个)
Walter Roberson
2019-3-18
true() and false() are functions that accept sizes. true(1) means the same as true(1,1) which gives you a 1 x 1 array of values all of which contain true. false(0) means the same as false(0,0) which gives you a 0 x 0 (empty) array of values that would all be false if there were any elements there. You should just be using true and false not those followed by a size.
You should remove the
AllNonZero(a);
call that you have at the top of your file.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!