Search code examples
matlabinterpolationderivative

Get derivative numerically


I have 2 vectors and a scalar:

  • grid which is (N x 1);
  • Value which is (N x 1);
  • sval which is (1,1);

If I want to interpolate sval on grid I know that I can simply do:

intervalue = interp1(grid, Value, sval, 'PCHIP');

What if now I want the derivatives, i.e. the slope of the function Value at that particular point sval?


Solution

  • As mentioned in the comments, you can approximate the derivative by forward finite difference approximation:

    slope = diff(Value) ./ diff(grid);
    

    Alternatively:

    slope = gradient(Value(1:end-1),grid);
    

    This is a simple method of numerical differentiation. For a detailed guide on numerical differentiation in MATALB, see this answer.

    Here is an example of the finite difference method with the desired interpolation:

    % Define function y = x^3
    grid = 1:100;
    Value = grid .^ 3;
    
    % Approximate derivative via the local slope
    slope = diff(Value) ./ diff(grid);
    % Or: slope = gradient(Value(1:end-1),grid);
    slope_grid = grid(1:end-1);
    
    % Interpolate derivative
    sval = 33.5;
    sval_slope = interp1(slope_grid, slope, sval, 'PCHIP');
    

    We can visualize the result:

    figure;
    plot(grid, 3*grid.^2)
    hold on
    plot(slope_grid, slope)
    legend('Reference', 'Approximation', 'Location', 'NorthWest')
    

    enter image description here