Passing a 1xn array into a function handle instead of individual values for Matlab?

39 views Asked by At

I'm trying to find a way to pass a 1xn array into a function handler with n being the number of variables in the function so let's suppose I declare a handler as such:

U = @(x, y) x^2 + 2*y^2

and plugged in:

U(1, 2)
ans = 
     9

Is there some way I can do something similar to this instead?

a = [1, 2]
U(a) 
ans =
     9
1

There are 1 answers

2
such On

Yes you can;

U = @(x, y) x^2 + 2*y^2;
a = {1, 2};
U(a{:})

When you expand the contents of a cell {:} it expands as the separate values stored in the cell. This is different from myMatrix(...) or myCell(...) which both produces a subset of the original set (be it a cell or a matrix).