1

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?

phdstudent
  • 1,060
  • 20
  • 41
  • 1
    You can use the `diff` function to calculate differences between vector elements. so if you use `diff(value)` and then find the corresponding index and x difference you'll get your derivative – Max Mar 05 '17 at 20:14
  • 1
    Since you use `interp1` the derivative at `sval` should be the same as at anywhere within the two neighboring grid points. So you can first locate `sval` and then use @Max's method. – Yvon Mar 05 '17 at 20:25
  • Not sure I understood max s method. After using diff I get a vector of differences. Then I can get a vector of differences from grid (using the same method). The ratio would yield the derivative? Then on that new grid just locate the point closest to sval? (a more detailed answer that I can accept below is welcome :) ) – phdstudent Mar 05 '17 at 20:29

1 Answers1

4

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

Community
  • 1
  • 1
Richard
  • 1,020
  • 8
  • 16