Reputation: 6870
Suppose I want to create an anonymous function that does the following
f: [a, b] -> [a^2, b/2]
Since the operation is different on a
and b
I haven't been able to figure out how. Is this at all possible in matlab? My function will have the constraints R^2 -> R^2
Upvotes: 3
Views: 196
Reputation: 2919
Looking at the matlab help for anonymous functions looking at section functions with multiple inputs or outputs, I would think that you would be able to do something like the code below
Second edit Turns out if you use deal (as given by thewaywewalk) or if you dereference the anonymous function you can get the same thing.
crazyfunction=@(a,b) {(a^2),(b/2)};
[x y]=crazyfunction(a,b);
Quick and dirty test shows that this will give no syntax errors
>> f = @(x,y) {x^2, y/2};
>> f(2,2)
ans =
[4] [1]
EDIT Fired up matlab to see my original answer would actually work, doesn't look like it (see second edit you need to use {}).
You would either daisy chain two anonymous functions together in such a way that a and b are part of anonymous function c or use a struct of anonymous functions effectively as shown below
crazyfunction={@(a) (a^2); @(b) (b/2);}
[crazyfunction{1](7) crazyfunction{2}(9)]
ans =
49.0000 4.5
Upvotes: 3
Reputation: 25232
Though you already accepted PQL's answer your question actually reads like you're looking for this solution using deal
:
f = @(x,y) deal( x^2, y/2 );
[u,v] = f(2,2)
returning:
u =
4
v =
1
Upvotes: 4
Reputation: 132
Because of the specific constraints, it would have to be something like this:
f = @(x) [x(1)^2, x(2)/2];
You can't explicitly define outputs in an anonymous function any other way.
Upvotes: 5