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 Center および File ExchangeEntering Commands についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by