0

I have a task to write a function that has an optional output argument.

Let's say I have a function y = fun(a,b). From what I understood, depending on whether the user needs the value y, it will EITHER calculate y OR draw some diagram.

So I think it means that if user calls my function like this: z = fun(1,2), then it calculates y and returns it, but if he calls it like this: fun(3,4);, then it won't return anything and draw a diagram instead.

Is there any way to check how my function has been called inside it? If yes, then how?

Paolo
  • 21,270
  • 6
  • 38
  • 69
MartinYakuza
  • 60
  • 1
  • 12
  • You can use [varargout](https://www.mathworks.com/help/matlab/ref/varargout.html) to control the number of the output of a function, You can find an [example of how to use it](https://stackoverflow.com/a/48671290/4806927) in this my answer to similar question. Of course you have to pass a parameter to the function to be used as a flag to select the output – il_raffa Apr 30 '20 at 16:29

2 Answers2

2

You can use nargout here:

function y = q61527462(a,b)
    if nargout > 0
        % Calculate y
        y = a + b;
    else
        % Plot
        plot(a,b)
    end
end

so when you call the function as:

>> y = q61527462(1,2)

you get:

y =

     3

and when you call with:

>> q61527462(1,2)

you get the plot

Paolo
  • 21,270
  • 6
  • 38
  • 69
1

Have a look at nargout, that roughly translates to number of argument to output (there is also a nargin to check the number of input arguments).

However, the function will return the return-value anyway if your just check for nargin. You will also need to use varargout (variable argument output) to make your function return something only if the output will be assigned to some external variable.

So you just write in your function

function varargout = fun()

if nargout % implicit cast to a logical. It is equivalent to nargout > 0
    % return output
    varargout{1} = true; % note that this requires to wrap your output in a cell
else
    % do plotting
end

EDIT: It is even not necessary to use varargout. If you don't assign a value to a return-variable, it won't appear. So MATLAB can manage a not-assigned return-variable (something I was surprised to learn myself^^). This even works with multiple outputs!

max
  • 3,915
  • 2
  • 9
  • 25
  • 2
    You don’t need `varargout`, you can simply not assign to the output variable as shown in the other answer. Otherwise, nicely written answer! – Cris Luengo May 01 '20 at 13:36
  • oh that is true. Was this ever since or is it a new feature? I always thought it would be necessary – max May 01 '20 at 19:40
  • 1
    This has always been this way, at least since MATLAB 5.3 (1999) when I started using it seriously. – Cris Luengo May 01 '20 at 20:14