How do I take the derivative of my plot?

I have my temperature in the y axis, and my distance in the x. I have them all plotted out and I have the data too, how can I take the derivative of the plot?

 Accepted Answer

dy=diff(y)./diff(x)
plot(x(2:end),dy)

8 Comments

Additionally, the x vector should be shifted by half the interval size.
Hi, Abdelmalek, Is there anyway not to exclude any point from x ?
Why is it that when i use this code with two row vectors I get dy being 1 column shorter than before?
It looks like diff(x) is taking the difference between each number in the array. There is no number to compare the last number in the array to, so you will get one number less than the original array.
In the latest versions of matlab, you can use the gradient() function, which also avoids the issue Andrew Hiett mentioned.
dy=gradient(y(:))./gradient(x(:))
plot(x,dy)
gradient function is nice and easy. Thanks for sharing!
does that work when the derivative at some data points has 2 values (before and after the data point)?
I mean the derivative of the plot is not continuous in all points.
Torsten
Torsten on 23 Jan 2023
Edited: Torsten on 23 Jan 2023
If you only have discrete values for x and y, there is no method to tell you whether there is a discontinuity in the derivative of y in a point x_i.
You can compare (y(i+1)-y(i))/(x(i+1)-x(i)) with (y(i)-y(i-1))/(x(i)-x(i-1)), but even if both differ significantly, it's not possible to decide whether there is a discontinuity in the derivative at x=x(i).

Sign in to comment.

More Answers (1)

Call polyfit to generate your polynomial (if you don't already have a polynomial)
Call polyder to get derivative of your fitted line
Call polyval with your original X values to get the Y values of your derivative and plot that with hold on so it doesn't erase your original plot

1 Comment

Note that polyfit (any polynomial fit) will often be a terribly poor choice here, since many curves are not well fit by a polynomial model. For example, consider points that lie on the perimeter of a circle, or the function sqrt(x), near x==0. Or the function sin(x), over multiple periods. Or a classic problem function for polynomial fits, 1/(1+x^2).

Sign in to comment.

Tags

Asked:

on 19 Apr 2013

Edited:

on 23 Jan 2023

Community Treasure Hunt

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

Start Hunting!