Derivative of a multivariate function handle

6 ビュー (過去 30 日間)
Swami
Swami 2024 年 10 月 13 日
コメント済み: Matt J 2024 年 10 月 16 日
I have a function handle here with symbolic array variable 'y'. I would like to take derivative of the function for which I am using the eval function. But after this the symbolic array variable 'y' disappears and we have y1 and y2. So I cannot carry out the substitution as in the original function. Is there a way of preserving the symbolic array variable after differentiation? I need this as I will be using it later in fsolve. I actually have many such functions for which I would like to determine the variable array using fsolve later. The code below
syms y [1 2]
g = @(y) [y(1)*cos(y(2))+y(2)*sin(y(1))-0.5]
g = function_handle with value:
@(y)[y(1)*cos(y(2))+y(2)*sin(y(1))-0.5]
vpa(g([0.5 0.7]))
g1 = eval(['@(y)' char(-diff(g(y),y(1),1))])
g1 = function_handle with value:
@(y)-cos(y2)-y2*cos(y1)
g1([0.5 0.7])

回答 (2 件)

Matt J
Matt J 2024 年 10 月 13 日
編集済み: Matt J 2024 年 10 月 13 日
Is this what you want?
syms y [1 2]
g = [y(1)*cos(y(2))+y(2)*sin(y(1))-0.5];
Jfun=matlabFunction(jacobian(g,y))
Jfun = function_handle with value:
@(y1,y2)[cos(y2)+y2.*cos(y1),sin(y1)-y1.*sin(y2)]
Jfun(0.5,0.7)
ans = 1×2
1.3791 0.1573
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  2 件のコメント
Swami
Swami 2024 年 10 月 16 日
Yes, exactly! Thank you!
Matt J
Matt J 2024 年 10 月 16 日
If so, please Accept-click the answer.

サインインしてコメントする。


nick
nick 2024 年 10 月 13 日
Hi Swami,
I understand that you want to create a function handle for the differentiated function in which values can be substituted. You can use 'matlabFunction' function to convert the symboic function into function handle, as shown:
syms y [1 2]
g = @(y) [y(1)*cos(y(2))+y(2)*sin(y(1))-0.5];
vpa(g([0.5 0.7]))
g_diff = diff(g(y),y(1));
g1 = matlabFunction(g_diff, 'Vars', {y});
g1([0.5 0.7])
ans = 1.3791
You may refer to the following documentation to know more about 'matlabFunction' :
  1 件のコメント
Swami
Swami 2024 年 10 月 16 日
Yes, this is what I wanted! Thank you :)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by