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

时光总嘲笑我的痴心妄想 提交于 2019-11-28 19:17:15

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

If you'd rather not skip outputs using tilde ~ nor output a cell array, you'd only need an auxiliary anonymous function:

 deal2 = @(varargin) deal(varargin{1:nargout});
 myAnonymousFunc = @(x) deal2(x.^2, x.^3);

then you can obtain just the first output argument or both first and second one:

x = 2;
[b,a] = myAnonymousFunc(x)
b = myAnonymousFunc(x)

results:

b = 4

a = 8

b = 4

You can get multiple outputs from an anonymous function if the function being called returns more than a single output. See this blog post on the MathWorks website for examples of this in action.

There are two ways to get multiple outputs from an anonymous function:

  • Call a function which returns multiple outputs

    From the blog post linked to, they use the eig function like so

    fdoubleEig = @(x) eig(2*x)
    [e, v] = fdoubleEig(magic(3))
    
  • Alternatively you can construct an anonymous function which returns multiple outputs using the deal function.

    Here is one I made up:

    >>> f = @(x, y, z) deal(2*x, 3*y, 4*z)
    >>> [a, b, c] = f(1, 2, 3)
    
    a = 
         2
    b = 
         6
    c = 
         12
    

Edit: As noted by Sam Roberts, and in the blog post I link to, you must use the correct number of output arguments when using deal, otherwise an error is thrown. One way around this is to return a cell of results. For example

>>> f = @(x, y, z) {2*x, 3*y, 4*z}

>>> t = f(1, 2, 3)

>>> [a, b, c] = t{:}

    a = 
         2
    b = 
         6
    c = 
         12
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!