Matlab code for the following

3 views (last 30 days)
Velika D'Souza
Velika D'Souza on 24 Jul 2017
Edited: Jan on 27 Jul 2017
How do i use central differencing for x=sint(t) over the interval 0 to 2pi with 2nd order accuracy?

Answers (1)

Jan
Jan on 25 Jul 2017
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 Comments
Velika D'Souza
Velika D'Souza on 25 Jul 2017
Edited: Jan on 27 Jul 2017
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 on 27 Jul 2017
Edited: Jan on 27 Jul 2017
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)

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices 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!