Reputation: 43833
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
Upvotes: 2
Views: 426
Reputation: 112659
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{:})
Upvotes: 2
Reputation: 2028
Does this work?
F=@(x)6+2*x(1)^1+3*x(2)^2;
xx = [1 2];
F(xx)
ans =
20
Upvotes: 0