Matlab – Wanted: Matlab example of an anonymous function returning more than 1 output

anonymous-functionargumentsfunctionMATLAB

I use anonymous functions for simple data value transforms. The anonymous functions are defined with the following syntax

sqr = @(x) x.^2;

I would like to have a simple anonymous function that returns more than one output that can be used as follows . . .

[b,a] = myAnonymousFunc(x);

The Matlab documentation suggests that this is possible, but it does not give an example of the syntax needed to define such a function.

http://www.mathworks.co.uk/help/techdoc/matlab_prog/f4-70115.html#f4-71162

What is the syntax to define such a function [in a single line, like the code example at the top of my post]?

Best Answer

Does this do what you need?

>> f = @(x)deal(x.^2,x.^3);
>> [a,b]=f(3)
a =
     9
b =
    27

With this example, you need to ensure that you only call f with exactly two output arguments, otherwise it will error.

EDIT

At least with recent versions of MATLAB, you can return only some of the output arguments using the ~ syntax:

>> [a,~]=f(3)
a =
     9
>> [~,b]=f(3)
b =
    27
Related Topic