-1

In Matlab, why do differentiation of Bessel function j1(x) for let us say x= 1:10 gives 9 values instead of 10?

x=1:10

J = besselj(1,x)

d_J = diff(J)

x =

     1     2     3     4     5     6     7     8     9    10


J =

  Columns 1 through 7

    0.4401    0.5767    0.3391   -0.0660   -0.3276   -0.2767   -0.0047

  Columns 8 through 10

    0.2346    0.2453    0.0435


d_J =

  Columns 1 through 7

    0.1367   -0.2377   -0.4051   -0.2615    0.0509    0.2720    0.2393

  Columns 8 through 9

    0.0107   -0.2018
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
user3914003
  • 1
  • 1
  • 2
  • Read doc on [diff](http://www.mathworks.in/help/matlab/ref/diff.html) ? – Divakar Aug 06 '14 at 11:12
  • 1
    Because `diff` just computes _differences_ between consecutive values. The number of differences is one less than the number of values. Of course, you can use those differences to approximate the _derivative_ of the function, which is perhaps what you want. – Luis Mendo Aug 06 '14 at 11:13
  • 1
    Please pay attention to proper formatting. – Schorsch Aug 06 '14 at 13:08

2 Answers2

1

diff applied on a numerical vector just computes differences between consecutive values. The number of differences is one less than the number of values. Of course, you can use those differences to numerically approximate the derivative of the function.

If you want to compute the derivative directly, you can do it with symbolic computation (see Matlab Symbolic Toolbox). When applied on a symbolic function, diff does give you the derivative:

>> syms x; %// define symbolic variable
>> f = besselj(1,x); %// define symbolic function
>> g = diff(f ,x) %// compute derivative
g =
besselj(0, x) - besselj(1, x)/x

You can then evaluate the derivative at specific values using subs:

>> subs(g, 1:8)
ans =
    0.3251   -0.0645   -0.3731   -0.3806   -0.1121    0.1968    0.3007    0.1423 
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

To differentiate a function numerically, you should use smaller steps and the gradient function:

x = 1:0.01:10;
J = besselj(1,x);
dJ = gradient(J,x);  % or: dJ = gradient(J)./gradient(x);
plot(x,J,x,dJ)

The second numerical derivative can be obtained with

dJ2 = 4*del2(J,x);  % or: dJ2 = 4*del2(J)./gradient(x).^2;
plot(x,J,x,dJ,x,dJ2)
Daniel1000
  • 779
  • 4
  • 11