Reputation: 222511
I was using matlab a lot to help me with math problems.
Right now I am looking for a way to do implicit differentiation in matlab.
For example, I would like to differentiate y^3*sin(x)+cos(y)*exp(x)=0
with respect to dy/dx
.
I am aware how to do this normally using math methods, but I was struggling to find the easy way with matlab. When I need normal differentiation ( find differential from f(x) ), I was using symbolic math toolbox and did something like this:
syms x
y = myfunctionOf(x)
diff(y)
I looked through doc diff
and also made a quick lookup in symbolic toolbox, but found nothing to help me with the above mentioned case. But I just refuse to believe that matlab does not have such a simple function.
Upvotes: 3
Views: 7541
Reputation: 144
The best way is always the easiest one!
syms x y(x)
f = y^3*sin(x)+cos(y)*exp(x);
diff(f,x)
also you can include pretty command for better visualization!
pretty(ans) %"Pretty print" output
Also, there are another way:
syms x y f
f = y^3*sin(x)+cos(y)*exp(x);
-diff( f, x )/diff( f, y )
pretty(ans) %"Pretty print" output
Enjoy it!
Upvotes: 2
Reputation: 363
Here is some code that does what you want, all explanation are in the comments, note that this code assumes that you want Matlab to do almost all of the Mathematical thinking for you.
%// Firstly you need to define a function `f` in terms of `x` and `y`.
syms x y;
f = y^3*sin(x)+cos(y)*exp(x);
%// Then you need to tell Matlab that y is a function of x,
%// you do this by replacing y with y(x)
yOfx = sym('y(x)');
f_yOfx = subs(f, y, yOfx);
%// Then you need to differentiate with respect to x
df = diff(f_yOfx, x);
%// df will have diff(y(x), x) terms in it,
%// we want to solve for this term,
%// to make it easier we should first replace it with a variable
%// and then solve
syms Dy;
df2 = subs(df, diff(yOfx, x), Dy);
dyOver_dx = solve(df2, Dy);
%// Finally if we do not want all of the y(x) terms,
%// then replace them with y
dyOver_dx = subs(dyOver_dx, yOfx, y)
Of course if we do not mind do a bit of paper work, we can get dy/dx = -(partial f/partail x)/(partial f/partial y)
from which we can get the much shorter code
%// Implicit differentiation identity
also_dyOver_dx = -diff(f, x)/diff(f, y);
Here is a check that the two answers are the same.
simplify(dyOver_dx - also_dyOver_dx) %// == 0
Upvotes: 3
Reputation: 7742
You could try using:
diff(expr, sym('v')) //This differenciates the expression respect to v
Upvotes: -1