How to output optional variables in a function?
102 次查看(过去 30 天)
显示 更早的评论
Hi, I have a function where i want to either output a, b OR c given my input condition which is found in num.
I am getting an error. Output argument "b" (and maybe others) not assigned during call.
Can you please suggest a solution!
For example,
if num=2, i want to output a=10, b=5 and if num=4, i want to output c=100
function [a,b,c] = trial_function(num)
if num==2
a=10;
b=5
else if num==4
c=100;
end
end
0 个评论
采纳的回答
Walter Roberson
2015-6-15
Whenever the user specifies a certain number of output variables on the left-hand side of an assignment, your routine needs to assign to at least that many variables starting from the left of the list.
So if the user only specifies 1 output such as if they called
v1 = trial_function(3)
then you would have to assign to at least the one variable in the left of your list, "a", and you could also assign to any of the other variables. It would, for example, be fine if you assigned to "a" and "c" but not "b" in this case; everything after the first one ("a") will be ignored.
If the user specifies two outputs, such as
[v1, v2] = trial_function(3)
then you need to assign to the first two outputs, "a" and "b", and you could also assign to any of the other variables; whatever you assign or do not assign to c will be ignored if the user only specifies two outputs. It would be an error to assign to "b" but not to "a" if the user requests two outputs.
If the user specifies
[v1, v2, v3] = trial_function(4)
then you would need to assign to all three outputs, "a", "b", and "c". The outputs v1, v2 would be given whatever value you assigned to "a" and "b": even if the user doesn't care what the values are, you must provide a value.
Please note that outside of your function, the outputs are considered only by position, not by name. If you were to do
c = trial_function(4)
then this would not match the "c" on the left side against the "c" of your output variable list: it goes strictly by position, so the outside "c" variable would be assigned the value of the variable in the first position of your list, what you call "a".
6 个评论
Walter Roberson
2020-5-25
My thought would be that your condition does not do exactly what you think it does. But it is difficult to say without the code and data to test with.
PBM
2020-5-29
It's a pretty long code so I did not post more than that here----- I will read through it again and see if I can pick it out
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!