Which method is used by diff ---Matlab differentiation

3 views (last 30 days)
Hi, I need to take a derivative for dp/dx My p array is 1*101 element denoted :
dt=0.0001; dx=0.01;
for numbert=1:1001
t=(numbert-1)*dt
for i=1:101
x(i)=(i-1)*dx
if x<t
p(i) = ....
else
p(i) = ...
end
end
end
1. I need to calculate dp/dx:: if x<t I must use backward differentiation with respect to x, if x>t I must use forward differentiation with respect to x.
2. I need to plot dp/dx against x
I have used diff for differentiation.
xd = diff([x(3),x,x(end-2)]);
pd = diff([p(3),p,p(end-2)]);
dpdx = (pd(1:end-1)./xd(1:end-1).*xd(2:end) ...
+ pd(2:end)./xd(2:end).*xd(1:end-1)) ...
./ (xd(2:end)+xd(1:end-1))
Which type of numerical differentiation does it use? I have to use central, forward and backward differentiation for 1*101 array valued function and 1*101 valued x.
  1 Comment
Stephen23
Stephen23 on 7 May 2015
Defining p inside of two nested for-loops is very awkward. If you showed us how p's values are calculated we could probably show you a much neater and faster method to generate these values using vectorized code.

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 7 May 2015
Edited: Stephen23 on 7 May 2015
If you are doing basic numeric calculations, then according to its documentation diff "calculates differences between adjacent elements of X..."
Not differentiation, just difference.
The diff documentation shows how this difference can be used for calculating an approximate numeric differentiation, just search for the example "Approximate Derivatives with diff", which is begins: "Use the diff function to approximate partial derivatives with the syntax Y = diff(f)/h..."
If you are defining symbolic variables or doing something else like that then you need to specify this in your question.
  6 Comments
Stephen23
Stephen23 on 8 May 2015
Edited: Stephen23 on 10 May 2015
Yes, you have a different number of elements in your vectors. This is perfectly consistent with the diff operation that is being performed: of course there are only 100 differences for 101 elements. If you want the number of points to be the same in these two vectors to be the same then you will have to either:
  1. interpolate the x values to somehow represent each interval with one x value: do you choose the start, the end or the middle of the interval? Why?
  2. use a different method to estimate the derivative at the x points: one option is to use gradient, or to fit splines and differentiate them. Have a search on the internet or on MATLAB Answers:
And remember there is no "right" way to do this... it depends on lots of factors, including the quality of data and your own needs.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!