Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Octave: functions doesn't return more than one value

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?

like image 990
Our Avatar asked Sep 05 '25 03:09

Our


1 Answers

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
like image 165
Suever Avatar answered Sep 08 '25 21:09

Suever