How can I solve a problem related to the output argument.
1 次查看(过去 30 天)
显示 更早的评论
% I will make the code simpler. Let's assume I have this code. And depending on the input value I want to show assign a=10 and b=5 different values (disregard the %value of the output C) or assign c=100 a value and disregard a and b.
function [a,b,c,d] = trial_function(num)
if num==2
a=4;
b=5
elseif num==4
c=100;
d=230
end
%I am getting an error. Output argument "b" (and maybe others) not assigned during call to
%Please, can you help me.Thank you.
0 个评论
采纳的回答
Ameer Hamza
2020-11-18
编辑:Ameer Hamza
2020-11-18
The name of output argument does not matte outside the function. If you just want to output two values for each case, just use
function [a,b] = trial_function(num)
if num==2
a=4;
b=5;
elseif num==4
a=100;
b=230;
end
Regardless, If you want to output 3rd and 4th argument in 2nd case, then you can set a and b to empty vectors
[~,~,x,y] = trial_function(4)
function [a,b,c,d] = trial_function(num)
if num==2
a=4;
b=5;
elseif num==4
a = [];
b = [];
c=100;
d=230;
end
end
If you want to output variable number of output arguments, then use varargout: https://www.mathworks.com/help/matlab/ref/varargout.html
更多回答(1 个)
Star Strider
2020-11-18
The way I usually deal with this is to define all the outputs as NaN in the beginning of the function. The ones that are assigned in the function will overwrite tha NaN value, and it is also easy to determine the values that were not assigned.
Example —
function [a,b,c,d] = trial_function(num)
[a,b,c,d] = deal(NaN);
if num==2
a=4;
b=5
elseif num==4
c=100;
d=230
end
end
.
2 个评论
Star Strider
2020-11-18
In my approach, the outputs are assigned NaN until they are assigned other values in the if blocks. If they are not assigned other values, they remain NaN. Assign them any value you wish, then modify that value later in the code.
Assigning them a specific value (whether NaN, 0, or something else) avoids throwing the warning or error if the values are not assigned in the if blocks. It will also indicate which values are not assigned, since those will be NaN (or any other default value).
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!