How do I create a vector function from a symbolic expression?
5 views (last 30 days)
Show older comments
MathWorks Support Team
on 19 Jun 2018
Answered: MathWorks Support Team
on 20 Jun 2018
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?
Accepted Answer
MathWorks Support Team
on 19 Jun 2018
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.
0 Comments
More Answers (0)
See Also
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!