Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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]?

like image 220
learnvst Avatar asked May 17 '12 11:05

learnvst


1 Answers

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 
like image 135
Sam Roberts Avatar answered Sep 17 '22 14:09

Sam Roberts