MATLAB: How to create a vector function from a symbolic expression

expressionfunctionmatlabfunctionsymbolicSymbolic Math Toolboxvector

I can create a MATLAB function from a symbolic expression using the following method:
>> syms a b c
>> symExp = a .* b + c
>> scalarFcn = matlabFunction(symExp)
scalarFcn =
function_handle with value:
@(a,b,c)c+a.*b
I would like a programmatic way to turn this symbolic expression into a vector function of the vector [a, b, c] like this:
>> vectorFcn = @(theta) theta(1) .* theta(2) + theta(3)
Is this possible?

Best Answer

The "matlabFunction" function allows you to specify the desired input arguments using the "Vars" option. The following example will generate the desired function:
>> syms a b c
>> symExp = a .* b + c;
>> vectorFcn = matlabFunction(symExp, 'Vars', {symvar(symExp)});
The "symvar" function takes a symbolic expression and returns an array of the symbolic variables use in that expression in alphabetical order.
This array is then placed in a cell array when specifying the input arguments to the generated function. This indicates that the specified arguments are meant to be passed as a single vector.
The newly generated function can be called as follows:
>> vectorFcn([1 2 3])
ans =
5
This method will work for any symbolic expression. However, remember that the order of elements in the vector must correspond to the symbolic variables of the expression in alphabetical order.
If instead you would like to directly specify an order, you can simply replace the call to "symvar" with an array of symbolic variables:
>> vectorFcn = matlabFunction(symExp, 'Vars', {[a b c]});
This gives you more freedom, but you will have to change the array if different symbolic variables are used.