I'm trying to model the collisions of a ball and its x and y position over a certain period of time in a 500 by 500 box. Whenever I try to run the script for different time steps( h
), I keep getting the error:
Subscripted assignment dimension mismatch.
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;
Simple fix: use cell arrays:
xout3{j} = xout2;
yout3{j} = yout2;
You define t
in steps of h
, and since h
becomes smaller, t
increases in length, thus also your xout2
. Cell arrays allow for dissimilar sized matrices, and you call them with curly braces instead of round ones.
Note that it is bad practise to use i
or j
as a variable . Also try and refrain from using global
variables, it is better to pass your variables to the actual function, see the modified code:
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
Script:
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
Results in:
xout3 =
[1x5001 double] [1x50001 double] [1x500001 double]
yout3 =
[1x5001 double] [1x50001 double] [1x500001 double]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.