Error With Output Argument Not Assigned to a Value Function
显示 更早的评论
So I have this small function here, which takes in a user input and prints the output sum. However, if the numbers don't fall into a range, it will print an error message and not perform the calculation.
However, if I use lets say (2, 3) for example, my function will run, and it will display "Error". However after that I get the message :
Output argument "calc" (and possibly others) not assigned a value in the execution with "math_example" function.
function [calc] = math_example(input1, input2)
if (input1 > 0 || input2 < 0)
disp("Error")
else
calc = input1 + input2;
disp(calc);
回答(1 个)
Voss
2022-2-20
0 个投票
It's printing a message that says "Error", but it's not throwing an error per se. Therefore, execution continues and you get the error you saw because calc was undefined when the function finished.
You should call error() to actually throw an error, if that's the desired behavior, or set calc to some value, e.g., [] (and if necessary check for that value in the calling function).
And/or you could have a second output argument indicating the error, but in any case you should make sure all required output arguments (see nargout) are defined when the function completes, no matter how it terminates.
2 个评论
Voss
2022-2-21
Yes, you have to set calc to something. I recommend using a value that cannot happen in any non-erroneous situation (to use your example code, 0 could be a valid result of adding two scalar numbers; the empty array would never the valid result of adding two scalar numbers, so it can be used to indicate that the error state occurred).
类别
在 帮助中心 和 File Exchange 中查找有关 Image Arithmetic 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!