I know in matlab, index start from 1, not 0; How come I get an error on line k1 saying index exceeds matrix dimension even though for loop starts from 2?
5 views (last 30 days)
Show older comments
real x1;
real x2;
span=[0,4];
h=.04;
x10=0;
x20=1;
x1(1)=x10;
x2(1)=x20;
step= 100;
f=@(x1,x2) -3*x2;
f1=@(x1,x2)(1/3)*x1;
for j=2:step
x1(j,1)=x1(j-1)+h;
k1(j-1,1)=h*f( x1(j-1), x2(j-1)); % index exceeds matrix dimension
k2(j-1,1)=h*f( x1(j-1)+h/2, x2(j-1)+0.5*k1(j-1) );
k3(j-1,1)=h*f( x1(j-1)+h/2, x2(j-1)+0.5*k2(j-1) );
k4(j-1,1)=h*f( x1(j-1)+h, x2(j-1)+k3(j-1) );
y1(j,1)=x2(j-1)+(1/6)*(k1(j-1)+2*k2(j-1)+2*k3(j-1)+k4(j-1));
end
0 Comments
Accepted Answer
Birdman
on 5 Apr 2018
Because you did not do any preallocation for k1, k2, k3 and k4. Add this code before your loop and after the definition of step:
k1=zeros(step-1,1)
k2=zeros(step-1,1)
k3=zeros(step-1,1)
k4=zeros(step-1,1)
y1=zeros(step,1)
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!