I'm am having trouble writing a derivative function.
Mostra commenti meno recenti
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.
1 Commento
Risposta accettata
Più risposte (2)
Youssef Khmou
il 14 Feb 2013
Hi, try this :
function [ der ] = derivative(f,nsamp,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 = 0:dx:n-dx;
L = length(vect);
der=zeros(1,L);
for i = 1:L-1
der(i) = (f(i+dx)-f(i))/dx;
%OR : der(i) = (f(i+dx)-f(i))/(vect(i+1)-vect(i));
end
der(end)=der(end-1);
3 Commenti
Youssef Khmou
il 14 Feb 2013
Compare it with "diff" function , i think this function needs more resolution,
Jan
il 14 Feb 2013
No, this does not work also: You do not want "f(i+dx)", where "i" is the run index of the FOR loop. The derivative should be evaluated at the points x:dx:(x+nsamp*dx).
Youssef Khmou
il 14 Feb 2013
yes, right, i post new answ.
Youssef Khmou
il 14 Feb 2013
Hi, Becca
The first answer has prob, here is a fast way :
function [ der ] = derivative(f,x,dx)
%derivative This function solves problem 5.19 in Chapman (2008).
% x - starting value, or vector
% dx - step size
% nsamp - number of samples of the function
% f - function
% Original function
Y=feval(f,x);
xp=x+dx;
YP=feval(f,xp);
der=(YP-Y)/dx;
if length(x)>2
figure, plot(x,Y,x,der,'r')
end
Categorie
Scopri di più su Measurements and Statistics in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!