0

I have the following MWE that calculates the derivative of a function along the y-direction:

x=1:50;
y=x;

phi = sin((x-10)/10);



dyPhi = (4.0*(circshift(phi(:,:), [+0, +1]) - circshift(phi(:,:), [+0, -1])) + ...
         1.0*(circshift(phi(:,:), [+1, +1]) - circshift(phi(:,:), [-1, -1])) + ...
         1.0*(circshift(phi(:,:), [-1, +1]) - circshift(phi(:,:), [+1, -1])))/12.0;

figure(1)
imagesc(phi)
colorbar

figure(2)
imagesc(dyPhi)
colorbar

However, please take a look at the two plots: On the plot for dyPhi, it seems that the derivative has a wrong sign.

Why is that? If I swap the sign, then I get what I would expect.

BillyJean
  • 1,537
  • 1
  • 22
  • 39
  • Why exactly are you using `circshift`? There are more general ways of numerical differentiation or, if you are working only with `sin & cos`, you can simply "differentiate" by addition of `pi/2`. – Victor Pira Apr 08 '15 at 16:36

1 Answers1

0

You are calculating the derivative using f(x-1) - f(x+1), so the sign change is to be expected.

I would recommend gradient for numerical differentiation.

plot(x,y) is also more useful for visualizing functions, rather than imagesc.


With regards to your code, I'm a little confused by it.

y is a 1D vector, yet you seem to by trying to shift it in two dimensions with circshift(phi(:,:), [-1, +1]). The first shift dimension is irrelevant since y only has one row. This means that you are calculating the same thing three times, but scaling each result by 4.0, 1.0, and 1.0.

As I mentioned, circshift(phi,[0,1]) - circshift(phi,[0,-1]) is really calculating f(x-1) - f(x+1). circshift(phi,[0,1]) replaces each value f(x) with its past value f(x-1) because the shift is to the right. Likewise, a left shift with circshift(phi,[0,-1]) replaces f(x) with f(x+1).

eigenchris
  • 5,791
  • 2
  • 21
  • 30