ktobrien
ktobrien

Reputation: 17

Using a vector as an input for a function of multiple inputs in matlab

I want to use a vector input such of dimension [m;1] in a function that takes in m number of inputs. For example:

syms x1 x2;

f = x1^2 + x2^2;
F = matlabFunction(f);
x = [1;1];
F(x);

The above code does not work because F is a function of 2 inputs and it only sees the vector x as a single input. I know I can say F(x(1),x(2)) and the above would work but I want it to work for a function of m variables and a vector of m length.

All help is appreciated. Thanks.

Upvotes: 1

Views: 916

Answers (1)

Suever
Suever

Reputation: 65430

You will want to first convert x to a cell and then pass it with {:}.

xcell = num2cell(x);
F(xcell{:});

Alternately, you can specify that you want x1 and x2 to be passed as an array when you call matlabFunction using the Vars parameter.

F = matlabFunction(f, 'Vars', {[x1, x2]});
F([1 1]);

Upvotes: 3

Related Questions