MATLAB: How to output optional variables in a function

function callif elsevariable output

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

Best Answer

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".