3

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

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this does exactly what I want (how come I didnt think of this? :D)
4

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

1 Comment

thanks for the inspiration. I knew I was looking for something regarding cell arrays
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.