Eugene
Eugene

Reputation: 61

Computing mixed derivatives in MATLAB using syms and diff

I'm using MATLAB 2012b. I want to get d²/dxdy of a simple function:

f(x,y) = (x-1)² + 2y²

The documentation states that I can use syms and diff as in the following example:

> syms x y
> diff(x*sin(x*y), x, y)
ans =
    2*x*cos(x*y) - x^2*y*sin(x*y)

But doing the same I got the wrong answer:

> syms x y
> f = (x-1)^2 + 2*y^2;
> diff(f,x,y)
ans = 
    4*y

The answer is right if I use diff like this:

diff(diff(f,x),y)

Well, it's not a problem for me to use it this way, but nevertheless why is the first variant not working? Is it a version issue?

Upvotes: 1

Views: 461

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

The actual documentation from R2010a:

diff(expr) differentiates a symbolic expression expr with respect to its free variable as determined by symvar.

diff(expr, v) and diff(expr, sym('v')) differentiate expr with respect to v.

diff(expr, n) differentiates expr n times. n is a positive integer.

diff(expr, v, n) and diff(expr, n, v) differentiate expr with respect to v n times.

So, the command diff(f,x,y) is the last case. It would be equal to differentiating f w.r.t. x, y times, or w.r.t y, x times.

For some reason I don't quite understand, you don't get a warning or error, but one of the syms variables gets interpreted as n = 1, and then the differentiation is carried out. In this case, what diff seems to do is basically diff(f, y, 1).

In any case, it seems that the behavior changed from version to version, because in the documentation you link to (R2016b), there is an additional case:

diff(F,var1,...,varN) differentiates F with respect to the variables var1,...,varN

So I suspect you're running into a version issue.

If you want to differentiate twice, both w.r.t x and y, your second attempt is indeed the correct and most portable way to do that:

diff( diff(f,x), y )

or equivalently

diff( diff(f,y), x )

NB I checked the R2010a code for symbolic/symbolic/@sym/diff.m and indeed, n is defaulted to 1 and only changed if one of the input variables is a double, and the variable to differentiate over is set equal to the last syms variable in the argument list. The multiple syms variable call is not supported, nor detected and error-trapped.

Upvotes: 1

Romano
Romano

Reputation: 13

Syms is only creating symbolic variables.

The first code you execute is only a single derivative. The second code you provided differentiates two times. So I think you forgot to differentiate a second time in the first piece of code you provided.

I am also wondering what answer you expect? If you want 4*y as answer, than you should use

diff(f,y)

and not

diff(f,x,y)

Performing the second derivative is giving me zero?

diff(diff(f,x),y)

If you want 4 as answer than you have to do following:

diff(diff(f,y),y)

Upvotes: 0

Related Questions