Matlab code for the following

3 次查看(过去 30 天)
Velika D'Souza
Velika D'Souza 2017-7-24
编辑: Jan 2017-7-27
How do i use central differencing for x=sint(t) over the interval 0 to 2pi with 2nd order accuracy?

回答(1 个)

Jan
Jan 2017-7-25
Is this a homework? If so, what have you tried so far? You need 2 lines of code only and revealing the solution might be counter-productive.
Remember the definition of central differences:
dx(i) = (x(i+1) - x(i-1)) / (t(i+1) - t(i-1))
This can be simplified, because t is evenly spaced.
t = linspace(0, 2*pi, 100);
dt = t(2) - t(1);
If it is not a homework, you can find many tools for central differences in the FileExchange, e.g. the fast C-Mex https://www.mathworks.com/matlabcentral/fileexchange/29887-dgradient, which replies 2nd order approximations with even and not even spacing.
  2 个评论
Velika D'Souza
Velika D'Souza 2017-7-25
编辑:Jan 2017-7-27
I was unsure how to include the equally spaced samples so i divided the dt by the spacing. Here is the code I have so far
dx = zeros (length (X),1) % Pre-allocate the derivative
for k = 1: length(X) % 2nd order accuracy
if k > 2.513 % Backward differencing
dx(k) = (3/2*X(k) - 2*X(k-1) + 1/2*X(k-2) )/dt
else % Forward Differencing
dx(k) = (-3/2*X(k) +2*X(k+1) - 1/2*X(k+2) )/dt
end
end
Jan
Jan 2017-7-27
编辑:Jan 2017-7-27
k > 2.513 ??? If k starts at 1, X(k-1) and X(k-2) is not defined. At the margins you cannot use the double sides quotient of differences. So you have to explain, what you want to use instead.
The show formula are not backward and forward differences. This would change the indices, not only the sign of the output.
You did not answer my question if this is a homework. It is easier to assist you, when this is clear.
It seems like you have confused the formula for the 1st order approximation of the 2nd derivative with the 2nd order method for the 1st derivative. "Central differences" means:
Y = (X(3:end) - X(1:end-2)) / (2 * dt)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by