Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB force function to output n arguments

Tags:

matlab

Is there a way in matlab to force a function to output a certain 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 want: d(1:3) = practice() % d = [1 2 3]

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

like image 808
Hovestar Avatar asked Feb 22 '26 16:02

Hovestar


1 Answers

There is an option to let your function output everything when only a single 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 non uniform return data, it might be necessary to switch to a cell

If you wish not to change the function, you could use this a little bit more generic code:

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

Please not, that this returns a cell, not an array. That's because array to comma separated list conversion is not directly possible.

like image 200
Daniel Avatar answered Feb 25 '26 06:02

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!