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?

 채택된 답변

Chad Greene
Chad Greene 2017년 2월 21일

0 개 추천

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));

댓글 수: 6

By the way, the gradient function gives the same results.
t= 0: 1: 5;
y= [1 2.7 5.8 6.6 7.5 9.9];
plot(t,gradient(y,t))
Margaret Winding
Margaret Winding 2017년 2월 22일
편집: Margaret Winding 2017년 2월 22일
Thank you very much! I learned about the gradient function but my professor does not want us to use that for this problem.
I fixed the errors you mentioned, but it now gives me the same error "Subscript indices must either be real positive integers or logicals" but for dfdx=(y(2)-y(1))/(t(2)-t(1))
I don't understand what formatting error is occurring at this point, any ideas? Thank you so much!!
Torsten
Torsten 2017년 2월 22일
dfdx(1)=(y(2)-y(1))/(t(2)-t(1))
Best wishes
Torsten.
Chad Greene
Chad Greene 2017년 2월 22일
Ah, yes, sorry Margaret; thanks Torsten.
Margaret Winding
Margaret Winding 2017년 2월 23일
Chad and Torsten,
Thank you so much for your help! I was able to get the correct answer :)
alburary daniel
alburary daniel 2018년 8월 3일
and how will be the code for using a 4-point first derivative?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2017년 2월 21일

댓글:

2020년 5월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by