Error With Output Argument Not Assigned to a Value Function
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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);
0 comentarios
Respuestas (1)
Voss
el 20 de Feb. de 2022
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 comentarios
Voss
el 21 de Feb. de 2022
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).
Ver también
Categorías
Más información sobre Entering Commands en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!