2. Write a Matlab function that accepts a vector of values and returns a vector of derivatives at those points. You can assume that the values are given on an equally spaced array with spacing h. Use the two point central difference formula df dx = fi+1 − fi−1 2h for all points except the two endpoints. For the endpoints use a one-sided derivative that uses two points. The function should have the form
function df = derivative(f, h)
%derivative Calculate numrical derivative of a funcion
% f - vector of the function values at eqialy spaced points
% h - distance between these points
df = zeros(size(f));
df(1) = (f(2) - f(1)) / h;
for i=2:length(f)-1
df(i) = (f(i+1) - f(i-1)) / (2*h);
end
df(end) = (f(end) - f(end-1)) / h;
end
Comments
Leave a comment