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)); endendend
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