take derivative of a function
2 views (last 30 days)
Show older comments
Hi, I have a function that I defined, and I would like to take the first derivative of this function. I tried different ways. But the program does not work. I must missed something. Below is my code.
%y is independent variable, a and b are parameters;
function [f,c1,c2]=fun(y,a,b)
f=a*log(c1)+b*log(c2);
c1=y*a;
c2=y*b;
end
Then I tried to take the derivative of f with respect to y. And I also want to check the value of c1 and c2 (in terms of y). So I wrote the following code.
[f,c1,c2]=fun(y,a,b);
g=diff(f,y)
I got the following error message
"Undefined function or variable 'y'"
Please help. Thanks.
0 Comments
Accepted Answer
Walter Roberson
on 29 Apr 2016
syms y
before the [f,c1,c2] assignment.
2 Comments
Xin CUI
on 29 Apr 2016
Thanks. I got g as an expression in terms of y(independent variable) and a,b(parameters). Now the next step is to find the solution of g=0. I wrote the following x=fsolve(g,y0) but got error messages Error using lsqfcnchk (line 108) If FUN is a MATLAB object, it must have an feval method.
Error in fsolve (line 198) funfcn = lsqfcnchk(FUN,'fsolve',length(varargin),funValCheck,gradflag);
Could you see the problem?
More Answers (1)
KSSV
on 29 Apr 2016
Use symbolic expression:
syms f a b
f = a*log(y*a)+b*log(y*b)
df = diff(f)
2 Comments
Xin CUI
on 29 Apr 2016
Thanks. I got df as an expression in terms of y(independent variable) and a,b(parameters). Now the next step is to find the solution of df=0. I wrote the following x=fsolve(df,y0) but got error messages Error using lsqfcnchk (line 108) If FUN is a MATLAB object, it must have an feval method.
Error in fsolve (line 198) funfcn = lsqfcnchk(FUN,'fsolve',length(varargin),funValCheck,gradflag);
Could you see the problem?
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!