Taking derivative of a time based function?

I'm new to MatLab and want to plot out some time based functions.
As an example, I have a function y = ((t/T).^n).*exp(-t/T). I want to plot the function vs time (t), along with the derivative of the function vs t.
I'm trying to use the diff function, but it's not working right. Any suggestions? Below is my actual code:
T = 8;
n = 1;
t = 0:0.1:100;
y = ((t/T).^n).*exp(-t/T);
x = diff(y,t);
plot(t,y,t,x)

Answers (3)

T = 8;
n = 1;
t = 0:0.1:100;
y = ((t/T).^n).*exp(-t/T);
x = diff(y)./diff(t);
plot(t,y,t(1:end-1),x)
% or use gradient
T = 8;
n = 1;
t = 0:0.1:100;
y = ((t/T).^n).*exp(-t/T);
x=gradient(y,t)
plot(t,y,t,x)
Wayne King
Wayne King on 6 Dec 2013
Edited: Wayne King on 6 Dec 2013
Are you trying to differentiate symbolically or numerically?
T = 8;
n = 1;
t = 0:0.1:100;
y = ((t/T).^n).*exp(-t/T);
x = diff(y)./diff(t);
subplot(211)
plot(t,y); title('y(t)');
subplot(212)
plot(t(2:end),x); title('dy/dt')
Symbolically
syms t; % requires symbolic toolbox
g(t) = t/8;
h(t) = exp(-t/8);
y = g(t)*h(t);
x = diff(y,t);
subplot(211)
ezplot(y,[0 100])
subplot(212)
ezplot(x,[0 100])
The 'diff' function serves two purposes, one to take derivatives and the other to take finite differences. To make it take derivatives you have to declare the variables involved as type 'sym'. To use the numeric form as you have as an approximation you will need to divide the 'diff' output by the length of the 't' interval which in your case is 0.1 .

Asked:

Len
on 6 Dec 2013

Edited:

on 6 Dec 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!