MATLAB force function to output n arguments

Is there a way in Matlab to force a function to output a specific number of arguments? For example, this is what Matlab does:

function [a,b,c] = practice
    if nargout >=1
        a =1;
    end
    if nargout >=2
        b=2;
    end
    if nargout ==3
        c = 3;
    end
end

d(1:3) = practice()
% d = [1 1 1]

      

I would like: d (1: 3) = practice ()% d = [1 2 3]

Can I get this behavior without having to say [d (1), d (2), d (3)] = practice ()

+3


source to share


1 answer


There is an option to allow your function to output everything when only one output argument is used:

function varargout=nargoutdemo(x)
 varargout{1}=1;
 varargout{2}=2;
 varargout{3}=3;
 if nargout==1
  varargout={[varargout{:}]};
 end
end

      

For uneven return data, you may need to switch to a cell



If you don't want to change the function, you can use this slightly more general code:

out=cell(1,3)
[out{:}]=practice

      

Please don't need this to return a cell, not an array. This is because converting an array to a comma cannot be directly possible.

+5


source







All Articles