Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

Index exceeds dimensions error

1 Ansicht (letzte 30 Tage)
cee878
cee878 am 13 Feb. 2017
Geschlossen: MATLAB Answer Bot am 20 Aug. 2021
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 Kommentar
KSSV
KSSV am 13 Feb. 2017
You are trying to access t as a vector, but it is a scalar. Check it.

Antworten (1)

Star Strider
Star Strider am 13 Feb. 2017
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 Kommentare
cee878
cee878 am 13 Feb. 2017
Okay. I fixed it like this:
%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,1)=a;
y(1,1)=y0;
w=zeros(n+1,1);
s=zeros(n+1,1);
s(1,1)=a;
w(1,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(i+1,1)=y;
s(i+1,1)=t;
end
%truevals(1,1)=y0;
for i=4:n
%truevals=g;
r(i,1)=f(s(i),w(i));
y=y+(h/24)*(55*r(i,1)-59*r(i-1,1)+37*r(i-2,1)-9*r(i-3,1)); %predictor
display(y);
t=t+h;
y=y+(h/24)*(9*f(s(i+1,1),w(i+1,1))+19*r(i,1)-5*r(i-1,1)+r(i-2,1)); %corrector
w(i+1,1)=y;
s(i+1,1)=t;
end
But I don't get an error, but when my code runs, I get NaN values. I don't get what's wrong though.
Star Strider
Star Strider am 13 Feb. 2017
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.

Diese Frage ist geschlossen.

Community Treasure Hunt

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

Start Hunting!

Translated by