Index exceeds dimensions error
정보
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
이전 댓글 표시
I'm trying to code the predictor-corrector method, but I keep getting an "Index exceeds dimensions", and I don't see where the error is.
%function[t y]=abmpc4(f,a,b,y0,h)
f=@(t,y)((y/t)-(y/t)^2);
h=0.1;
a=1;
b=2;
y0=1;
n=(b-a)/h;
t(1)=a;
y(1)=y0;
w=[];
s=[];
s(1)=a;
w(1)=y0;
%RK4 method to get initial values
for i=1:3
k1=h*f(t,y);
k2=h*f(t+(h/2),y+(k1/2));
k3=h*f(t+(h/2),y+(k2/2));
k4=h*f(t+h,y+k3);
y=y+(k1+(2*k2)+(2*k3)+k4)/6;
t=t+h;
w=[w,y];
s=[s,t];
end
%truevals(1,1)=y0;
%Adams-Bashforth 4-Step
% i=4;
% y=y+(55/24)*h*f(s(i,1),w(i,1))-(59/24)*h*f(s(i-1,1),w(i-1,1))+(37/24)*h*f(s(i-2,1),w(i-2,1))-(9/24)*h*f(s(i-3,1),w(i-3,1)); %predictor
% %t=t+h;
% w(i+1,1)=y;
% s(i+1,1)=t;
for i=4:n
%truevals=g;
t=t+h;
y=y+(h/24)*(55*f(t(i),y(i))-59*f(t(i-1),y(i-1))+37*f(t(i-2),y(i-2))-9*f(t(i-3),y(i-3))); %predictor
y=y+(h/24)*(9*f(t(i+1,1),y(i+1,1))+19*f(t(i,1),y(i,1))-5*f(t(i-1,1),y(i-1,1))+f(t(i-2,1),y(i-2,1))); %corrector
w=[w,y];
s=[s,t];
end
댓글 수: 1
KSSV
2017년 2월 13일
You are trying to access t as a vector, but it is a scalar. Check it.
답변 (1개)
Star Strider
2017년 2월 13일
The error:
Index exceeds matrix dimensions.
Error in Elipses (line ###)
y=y+(h/24)*(55*f(t(i),y(i))-59*f(t(i-1),y(i-1))+37*f(t(i-2),y(i-2))-9*f(t(i-3),y(i-3)));
%predictor
The problem is that here ‘t’ is a (1x1) double and ‘i’ is 4. That condition with throw the error you see.
This situation:
q = pi
r = q(4)
will throw the same error.
댓글 수: 4
cee878
2017년 2월 13일
Star Strider
2017년 2월 13일
It is difficult for me to follow your code. The solution is for ‘t’ and ‘y’ to be vectors, since you are also referring to previous values as well as current values.
It will probably be best to preallocate those vectors prior to the loop. Consider in your initial assignments:
t = [a 0 0 0];
y = [y0 0 0 0];
s = [a 0 0 0];
w = [y0 0 0 0];
Those assignments will create your necessary vectors.
cee878
2017년 2월 13일
Star Strider
2017년 2월 13일
You need to update the vectors in your loops by subscripting them.
For example:
for i=4:n-1
. . .
y(n+1) = y(n) + ...
. . .
end
Then reference them appropriately in your other equations that use them, similar to what I outlined here. You will have to experiment.
이 질문은 마감되었습니다.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!