MATLAB has special command diff that takes a list of numbers and calculates the difference between each adjacent number.
For example: y = [1,3,8]; dy = diff(y) → [2,5].
Numerical derivative - diff(y)./diff(x) will give the slope of each interval for the lists of x and y values
For example: x = [0,1,3]; y=[1,5,4]; dydx=diff(y)./diff(x) → [4,-1] ./ [1,2] → [4,-0.5]
When using yp=diff(y)./diff(x) it is necessary to map it to an associated x value. Since calculating the slope of a line segment, someone can map the slope to one of three x values:
- • forward difference –to map the slope to the beginning point use xp=x(1:end-1)
- • backward difference – to map the slope to the end point use xp=x(2:end)
- • central difference –to map the slope to the midpoint use xp=x(1:end-1) + diff(x)./2
Another Example for better understanding - Forward, Backward, and Central Difference Illustrated
there are 6 values for t and have to plot the curve y(t)=(t/2)2 also plot the derivative of the adjacent points.
>> t=[0 1 2 3 4 5]
>> y = (t./2).^2 % the curve y(t)
y = [0 0.25 1.00 2.25 4.00 6.25]
>> plot(t,y) % y vs. t
>> dydt=diff(y)./diff(t) % derivative of adjacent points
dydt= [0.25 0.75 1.25 1.75 2.25]