# Multiple Outputs

I just had an interesting exchange with a customer. He was trying to have an anonymous function return multiple outputs.

### Inherent Multiple Outputs

You can inherently get multiple outputs from an anonymous function if the function being called returns more than a single output. Here's an example.

fdoubleEig = @(x) eig(2*x)
fdoubleEig =
@(x) eig(2*x)


Let's ask for a single output first.

eOnly = fdoubleEig(magic(3))
eOnly =
30.0000
9.7980
-9.7980


and now let's get 2 outputs, the eigenvalues and the eigenvectors.

[e,v] = fdoubleEig(magic(3))
e =
-0.5774   -0.8131   -0.3416
-0.5774    0.4714   -0.4714
-0.5774    0.3416    0.8131
v =
30.0000         0         0
0    9.7980         0
0         0   -9.7980


### Assembling Multiple Outputs

If you want to return multiple outputs and there isn't an existing function to do so, you can assemble the outputs using the function deal.

fmeanVar = @(x) deal(mean(x), var(x))
fmeanVar =
@(x) deal(mean(x), var(x))


Let's try to get a single output.

try
mOnly = fmeanVar(magic(3));
catch
disp('deal requires the exact number of outputs.')
lerr = lasterror;
disp(lerr.message)
end
deal requires the exact number of outputs.
Error using ==> deal
The number of outputs should match the number of inputs.


This doesn't work because deal is picky about the number of outputs it expects to see.

Now let's try with 2 outputs.

[m,v] = fmeanVar(magic(3))
m =
5     5     5
v =
7    16     7


The deal function now sees two left-hand sides and works.

### Thoughts?

I suspect you now understand this (for those who didn't already), but I suspect I can hear protests about how MATLAB should be smarter about this. If you have some concrete thoughts, I'd love to hear them here.

Published with MATLAB® 7.3

|

### コメント

コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。