diff(f) saying "Undefined function 'diff' for input arguments of type 'function_handle'." and diff(f(x)) giving"Undefined function or variable 'x'."

7 ビュー (過去 30 日間)
I am trying to differentiate an equation f(x) which is input as as function_handle (e.g: @(x) x^2) and evaluate at different points
When I call the function this snippet is in I make sure to first call syms x;
df=str2func(['@(x)' char(diff(f(x)))]);
X=repelem(Xlist,2);
%Creating the list of Y values and derivative values from the function and
%the points
Ylist=zeros(1,numel(X));
for i=1:numel(X)
Ylist(1,i)=vpa(subs(f,x,X(1,i)));
end
Dlist=zeros(1,numel(Xlist));
for i=1:numel(Xlist)
Dlist(1,i)=vpa(subs(df,x,Xlist(1,i)));
end
Whenever I use this version, I get the error "Undefined function or variable 'x'."
However, when I remove the '(x)' from f(x) in the first line and write:
df=str2func(['@(x)' char(diff(f))]);
X=repelem(Xlist,2);
%Creating the list of Y values and derivative values from the function and
%the points
Ylist=zeros(1,numel(X));
for i=1:numel(X)
Ylist(1,i)=vpa(subs(f,x,X(1,i)));
end
Dlist=zeros(1,numel(Xlist));
for i=1:numel(Xlist)
Dlist(1,i)=vpa(subs(df,x,Xlist(1,i)));
end
I get the error: "Undefined function 'diff' for input arguments of type 'function_handle'."
Are either of these syntaxes right? If so, why I am getting the errors?
  5 件のコメント
Konrad Brine
Konrad Brine 2019 年 8 月 26 日
Assuming I don't turn it back into a function handle, how do I pass the symbolic variable (x) into f to make it a symbolic expressions which diff(f(x)) can differentiate?

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

回答 (1 件)

Konrad Brine
Konrad Brine 2019 年 8 月 26 日
Figured it out entirely thanks to Walter Robinson.
syms x;
df=matlabFunction(diff(f(x)));
X=repelem(Xlist,2);
%Creating the list of Y values and derivative values from the function and
%the points
Ylist=zeros(1,numel(X));
for i=1:numel(X)
Ylist(1,i)=f(i);
end
Dlist=zeros(1,numel(Xlist));
for i=1:numel(Xlist)
Dlist(1,i)=df(i);
end
I added syms x; above the df line, and changed the df line to matlabFunction(diff(f(x)));

カテゴリ

Help Center および File ExchangeCalculus についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by