In order to address to my problem, let's consider the most basic function
function [x, z] = main ()
x = 1;
z = 2;
endfunction
When I execute this function the output is
ans = 1
whereas I should have gotten something like
ans = 1
2
So why is this happening? What is the problem?
If you need multiple values out of an Octave (or MATLAB) function, you need to explicitly ask for all of them. If you provide no output arguments, the default behavior is to provide only the first output (unless the user explicitly specifies that there should be no outputs varargout = {}
) and assign it to the variable ans
.
So, if you want two outputs you need to explicitly ask for both of them
[x, z] = main()
If you want your function to return an array of x
and z
when only one output is provided, you can use nargout
to detect how many output arguments were requested and modify the return values appropriately
function [x, z] = main()
x = 1;
z = 2;
% If there is one (or zero) outputs, put both outputs in the first output, otherwise
% return two outputs
if nargout < 1
x = [x; z];
end
endfunction
And then from outside of your function
main()
% 1
% 2
output = main()
% 1
% 2
[x, z] = main()
% x = 1
% z = 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With