Which method is used by diff ---Matlab differentiation

2 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2015-5-7
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.

请先登录,再进行评论。

回答(1 个)

Stephen23
Stephen23 2015-5-7
编辑:Stephen23 2015-5-7
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 个评论
Stephen23
Stephen23 2015-5-8
编辑:Stephen23 2015-5-10
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Spline Postprocessing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by