diff(f) saying "Undefined function 'diff' for input arguments of type 'function_handle'." and diff(f(x)) giving"Undefined function or variable 'x'."
显示 更早的评论
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 个评论
Walter Roberson
2019-8-26
Why not leave df as a symbolic expression instead making it a function handle?
Note by the way that you should be using matlabFunction to convert to function handle. There are some subtle bugs in using char() the way you do.
Konrad Brine
2019-8-26
编辑:Konrad Brine
2019-8-26
Walter Roberson
2019-8-26
If given a function handle then in most cases (but not all) you can pass a symbolic variable to the function to get out the symbolic expression, which you probably do not need to convert back to function handle.
Konrad Brine
2019-8-26
Walter Roberson
2019-8-26
syms x
Fx = f(x) ;
df = diff(Fx, x);
回答(1 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Calculus 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!