How do I create a vector function from a symbolic expression?
13 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2018-6-19
回答: MathWorks Support Team
2018-6-20
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?
采纳的回答
MathWorks Support Team
2018-6-19
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!