Anton Daneyko
Anton Daneyko

Reputation: 6503

How to determine if a Matlab function returns no values?

f.m:

function [] = f(the_only_argument)
% Do awesome things here
end

g.m:

function [value] = g(the_only_argument)
% Do awesome things here
value = awesome_value;
end

Is there some sort of ReturnsNothing, such that:

assert(ReturnsNothing(@f) & ~ReturnsNothing(@g))

P.S. I want to be able to call arrayfun(@f, [1,1,1]), which currently returns an error:

??? Error using ==> f
Too many output arguments.

Upvotes: 0

Views: 252

Answers (2)

RTL
RTL

Reputation: 3587

Second part

arrayfun(@f, [1,1,1]) throws the error above as f has no input(s) defined, and arrayfun will call f for each value in the array (using that value as an input). so the error is identical to that which would be caused by f(1)

If you need a funciton to run in arrayfun which does not take an input you can wrap it in an anonymous function which junks the input.
For example

arrayfun(@(~)f,[1,1,1])

causes no errors, as arrayfun doesn't require outputs!

First part

nargout can be used outside of a function to check how many defined outputs it has by passing a string containing the function name

e.g. using functions from question

nargout('f')

ans =

     0

nargout('g')

ans =

     1

Furthermore if varargout is present it counts it as a single output but returns a negative value to indicate its presence

for example with the following function

function [value,varargout] = h()
...code
end

it returns

nargout('h')

ans =

     -2

Upvotes: 3

Sam Roberts
Sam Roberts

Reputation: 24127

Do nargout('f') and nargout('g') do what you need?

Be careful if you have functions with a variable number of output arguments, as nargout will return a negative number for that special case.

Upvotes: 5

Related Questions