How do I create a vector function from a symbolic expression?

조회 수: 5 (최근 30일)
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
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개)

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by