How to plot the derivative from experimental data
627 views (last 30 days)
Show older comments
Sreedhar
on 19 May 2014
Commented: Shiva Vikram Bhagavatula
on 15 Sep 2023
Hi I have a number of points (experimental data) plotted as an x-y plot. I want to generate the derivative of y w.r.t x from this plot. Is there a function in MATLAB which can do this ?
TIA
0 Comments
Accepted Answer
Star Strider
on 19 May 2014
Edited: Star Strider
on 25 Mar 2019
Not a specific MATLAB function, but it’s easy:
dydx = diff(y(:))./diff(x(:));
If you want dydx to be the same length as x and y (so you can plot it against x), ‘zero-pad’ the first value with eps:
dydx = diff([eps; y(:)])./diff([eps; x(:)]);
Both produce a column vector, so you may have to transpose it if x is a row vector in order to plot it with the others.
UPDATE — (24 Mar 2019 00:30)
A much more accurate approach would be:
dydx = gradient(y(:)) ./ gradient(x(:));
5 Comments
Star Strider
on 1 Jan 2022
Assuming vector arguments, the diff function takes the differences between successive elements of the vector, so the outputt is one element shorter than the arguments. The gradient function uses a central difference approximation of the derivative (except at the ends, where it calculates a simple difference) so the output has the same number of elements as the argument.
See the documentation on both for details.
.
Shiva Vikram Bhagavatula
on 15 Sep 2023
The function sampling may be poor at some or all points if completely different results are obtained for diff and gradient. For example,let the derivative be calculated at point 2 in a set of three points (p1,p2,p3). Assuming the spacing along the independent variable axis is dx, diff produces (p2-p1)/dx . Gradient produces (p3-p1)/(2dx). For them to be equal, the condition is (p3+p1)/2=p2,i.e; all three points are collinear( lie on the same straight line). The difference between gradient and diff would be a measure of the deviation of the points from the collinear fit.
More Answers (1)
Abhinendra Singh
on 27 Nov 2017
Hello, Can any one of you please post a working example of the above problem?
I appreciate the help!
3 Comments
John D'Errico
on 1 Jan 2022
Um, only one call to gradient needed.
x = 0:0.1:10;
y = sin(x);
plot(x, gradient(y,x));
When gradient is called with TWO arguments, it assumes you have passed in x also as the second argument. Now it computes a derivative estimate at each point. A simple finite difference scheme is used.
help gradient
See Also
Categories
Find more on Descriptive Statistics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!