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 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Birdman
2018-4-5
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!