2

In my matlab script, I have a function handler

F=@(x1,x2)6+2*x1^1+3*x2^2;

This gives me an anonymous function as F that takes 2 arguments and returns the value. I also have an array of values

x = [1 2];

With the above, how can I do

F(x)

In other words, something like F(1, 2) but I want to use x, I don't want to hard code values, and it also needs to work for any dimension size, I don't want to hard code it for 2-dimension like in the above example. Basically what I'm looking for is a way to turn an array into arguments.

Can this be done in matlab?

Thanks

1
  • +1 for the great, concise wording: "turn an array into arguments" Commented Mar 6, 2014 at 19:53

2 Answers 2

2

To turn an array into its arguments: first turn the array into a cell array (with num2cell), and then turn the cell array into a comma-separated list (with {:}):

xcell = num2cell(x);
F(xcell{:})
Sign up to request clarification or add additional context in comments.

2 Comments

@omega It's a clever answer. Don't forget to upvote.
0

Does this work?

F=@(x)6+2*x(1)^1+3*x(2)^2;
xx = [1 2];
F(xx)
ans =

    20

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.