MATLAB: I’m am having trouble writing a derivative function.

derivativehomework

I have to assume that a vector vect contains nsamp samples of a function taken at a spacing of dx per sample. Write a function that will calculate the derivative of this vector from the equation f'(x_i)= (f(x_i+1) – f(x_i)) / (x_i+1 – x_i). Also the function should check to make sure that dx is greater than zero to prevent divide-by-zero errors in the function. The function must also be able to have a starting at x = 0.
Here is what I have so far:
function [ der ] = derivative( f, nsamp,x, dx )
%derivative This function solves problem 5.19 in Chapman (2008).
% x - starting value
% dx - step size
% nsamp - number of samples of the function
% f - function
n = nsamp*dx;
vect = x:dx:n-dx;
L = length(vect);
while dx > 0
for i = 0:L
der(i) = (f(i+dx)-f(i))/((i+dx)-(i));
end
end
end
And when I go to the command window I get:
>> f=@(x)sin(x);
>> derivative(f,100,0,0.05)
Attempted to access der(0); index must be a positive integer or logical.
Error in derivative (line 21)
der(i) = (f(i+dx)-f(i))/((i+dx)-(i));
I'm having trouble fixing the errors and getting the program to run. Any help will be appreciated.

Best Answer

At first you have to consider that Matlab's indices are 1-based. So 1 is the minimal index and you'd need: for i = 0:L.
But your function contains much more problems:
  • while dx > 0 will produce an infinite loop, because dx does not change its value inside the loop.
  • ((i+dx)-(i) is exactly dx.
  • vect is not used for the calculations.
I'd restart from scratch:
  1. Redefine vect: It should start at x, have nsamp elements, and stop at x + nsamp * dx, correct?
  2. Evaluate the function in one step: y = f(vect);
  3. Use diff to calculate the difference between the elements of y with a loop. Dividing the result by dx produces the derivative already.
  4. The replied NaNs for dx==0 are ok, because this is mathematically consistent. And negative dx are ok also.
So you actually need 2 to 3 lines of code.