フィルターのクリア

How to calculate gradients of a symbolic function

17 ビュー (過去 30 日間)
Chugh
Chugh 2019 年 3 月 13 日
コメント済み: Torsten 2022 年 9 月 8 日
Hi,
I have a symbolic function of the form f = 2*y*z*sin(x) + 3*x*sin(z)*cos(y) and want to calcuate gradients with respect to x, y and z. I cannot define syms x y z before creating the function as its an input. Therefore, I defined syms x y z afterwards but its not working. The follwing error appeared:
Unable to convert expression into double array.
How do I calcuate gradients of this symbolic function?

採用された回答

Walter Roberson
Walter Roberson 2019 年 3 月 13 日
%construct the input
syms x y z
f(x,y,z) = 2*y*z*sin(x) + 3*x*sin(z)*cos(y);
%and assume you are passing f into a different function so x y z are not still around
g = yadayada(f);
function g = yadayada(f)
%so we have an input symbolic function but for some reason
%we are not in the context where the variables came from.
%it turns out to be as simple as
g = gradient(f);
%or for greater certainty you could
g = gradient(f, symvar(f)); %which is what the simple call does
%or perhaps you have a reason to do
syms x y z
g = gradient(f(x, y, z), [x y z])
%for example it might be a symbolic function in three other
%variables that you want to re-label as x, y, z.
end

その他の回答 (1 件)

Dirk
Dirk 2022 年 9 月 8 日
How do I etermine the intervals on which a function is increasing and decreasing for x ϵ [0,4]
  1 件のコメント
Torsten
Torsten 2022 年 9 月 8 日
syms x
f = x.*cos(x.^2)-exp(sqrt(x))+x.^3-4*x.^2;
df = diff(f,x);
f = matlabFunction(f);
df = matlabFunction(df);
x = 0:0.01:4;
plot(x,f(x))
x0 = [1.75 2.25];
sol(1) = fzero(df,x0);
x0 = [2.25 2.75];
sol(2) = fzero(df,x0);
x0 = [2.75 3.2];
sol(3) = fzero(df,x0);
x0 = [3.25 3.6];
sol(4) = fzero(df,x0);
x0 = [3.75 4];
sol(5) = fzero(df,x0);
sol
sol = 1×5
2.0016 2.4741 3.0614 3.5959 3.9127

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by