# second order finite difference scheme

119 views (last 30 days)
Margaret Winding on 21 Feb 2017
Commented: Rena Berman on 14 May 2020 at 16:22
I am given data t=[0 1 2 3 4 5] and y(t)=[1 2.7 5.8 6.6 7.5 9.9] and have to evaluate the derivative of y at each given t value using the following finite difference schemes.
(y(t+h)y(th))/2h =y(t)+O(h^2)
(y(t+2h)+4y(t+h)3y(t))/2h =y(t)+O(h^2)
(y(t2h)4y(th)+3y(t))/2h =y(t)+O(h^2)
I started the code, but I haven't learned what to do in the second order case. This what I have so far for the first given equation:
t= 0: 1: 5;
y(t)= [1 2.7 5.8 6.6 7.5 9.9];
n=length(y);
dfdx=zeros(n,1);
dfdx(t)=(y(2)-y(1))/(t(2)-t(1));
for i=2:n-1
dfdx(1)=(y(i+1)-y(i-1))/(t(i+1)-t(i-1));
end
dfdx(n)=(y(n)-y(n-1))/(t(n)-t(n-1));
the error that returns is "Subscript indices must either be real positive integers or logicals." referencing my use of y(t). How do I fix this to make my code correct?

#### 1 Comment

Rena Berman on 14 May 2020 at 16:22

Chad Greene on 21 Feb 2017
There's no need for the (t) when you define y(t). Same with dfdx. Also, make sure you change dfdx(1) in the loop to dfdx(i).
t= 0: 1: 5;
y= [1 2.7 5.8 6.6 7.5 9.9];
n=length(y);
dfdx=zeros(n,1);
dfdx=(y(2)-y(1))/(t(2)-t(1));
for i=2:n-1
dfdx(i)=(y(i+1)-y(i-1))/(t(i+1)-t(i-1));
end
dfdx(n)=(y(n)-y(n-1))/(t(n)-t(n-1));

Chad Greene on 22 Feb 2017
Ah, yes, sorry Margaret; thanks Torsten.
Margaret Winding on 23 Feb 2017