我试图在一个500乘500的盒子中模拟一个球及其x和y位置在一段时间内的碰撞。每当我尝试运行不同时间步长(h
)的脚本时,我都会收到错误:
订阅的分配维度不匹配。
global h
h_vector=[0.1 0.01 0.001];
t=0:h:500;
for j=1:length(h_vector)
h=h_vector(j);
[xout2,yout2]=walls_euler_method2e;
xout3(j,:)=xout2;
yout3(j,:)=yout2;
end
xout3;
yout3;
function [xout2,yout2]=walls_euler_method2e
global h
f1=5;%dx/dt
f2=-3;%dy/dt
x(1)=0;
y(1)=0;
t=0:h:500;
r=5;%radius of ball
hit_vertical_wall_left_first=0;
hit_horizontal_wall_down_first=0;
vertical_wall_left=250;
vertical_wall_right=-250;
horizontal_wall_up=250;
horizontal_wall_down=-250;
for i=2:length(t)
x(i)=x(i-1)+h.*f1;
y(i)=y(i-1)+h.*f2;
if x(i)==vertical_wall_left-r
f1=-f1;
hit_vertical_wall_left_first=1;
elseif x(1)==vertical_wall_right+r&&hit_vertical_wall_left_first==1;
f1=-f1;
else
fl=f1;
if y(i)==horizontal_wall_down+r
f2=-f2;
hit_horizontal_wall_down_first=1;
elseif y(i)==horizontal_wall_up-r&&hit_horizontal_wall_down_first==1;
f2=-f2;
else
f2=f2;
end
end
end
xout2=x;
yout2=y;
答案 0 :(得分:1)
简单修复:使用单元格数组:
xout3{j} = xout2;
yout3{j} = yout2;
您以t
的步长定义h
,并且由于h
变小,t
的长度增加,因此xout2
也增加global
。单元格数组允许使用不同大小的矩阵,您可以用大括号而不是圆形大括号来调用它们。
请注意,它是bad practise to use i
or j
as a variable。另外,请尝试避免使用function [xout2,yout2]=walls_euler_method2e(h)
f1=5;%dx/dt
f2=-3;%dy/dt
x(1)=0;
y(1)=0;
t=0:h:500;
r=5;%radius of ball
hit_vertical_wall_left_first=0;
hit_horizontal_wall_down_first=0;
vertical_wall_left=250;
vertical_wall_right=-250;
horizontal_wall_up=250;
horizontal_wall_down=-250;
for ii=2:length(t)
x(ii)=x(ii-1)+h.*f1;
y(ii)=y(ii-1)+h.*f2;
if x(i)==vertical_wall_left-r
f1=-f1;
hit_vertical_wall_left_first=1;
elseif x(1)==vertical_wall_right+r&&hit_vertical_wall_left_first==1;
f1=-f1;
else
fl=f1;
if y(i)==horizontal_wall_down+r
f2=-f2;
hit_horizontal_wall_down_first=1;
elseif y(ii)==horizontal_wall_up-r&&hit_horizontal_wall_down_first==1;
f2=-f2;
else
f2=f2;
end
end
end
xout2=x;
yout2=y;
end
变量,最好将变量传递给实际函数,请参阅修改后的代码:
h_vector=[0.1 0.01 0.001];
for jj=1:length(h_vector)
t = 0:h_vector(jj):500;
[xout2,yout2]=walls_euler_method2e(h_vector(jj));
xout3{jj}=xout2;
yout3{jj}=yout2;
end
脚本:
xout3 =
[1x5001 double] [1x50001 double] [1x500001 double]
yout3 =
[1x5001 double] [1x50001 double] [1x500001 double]
结果:
NoticeDialogListener