Error With Output Argument Not Assigned to a Value Function

조회 수: 11 (최근 30일)
Alex Triq
Alex Triq 2022년 2월 20일
댓글: Voss 2022년 2월 21일
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
Voss 2022년 2월 20일
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
Alex Triq
Alex Triq 2022년 2월 20일
편집: Alex Triq 2022년 2월 20일
What if I just want to display the message "Error" instead of an actual error message? Would the only solution then be to just set calc equal a value like "0" after the disp("Error") line?
Voss
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).

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by