Index exceeds the number of array elements (1).
Show older comments
I want to create a movie with a for loop, but Index exceeds the number of array elements (1) is shown. Someone can tell me were is the error? The for loop without the condition works fine, but where i assign a condition, the error message appears. :( I just want that when y <= 0, the angle theta0 and v0 change to theta0 = atan(y(j-2)/(x(j)-x(j-2))) and v0 = 0.8v0.
clear, clc
g=9.81; theta0=45*pi/180; v0=5;
t(1)=0;x=0;y=0;
plot(x,y,'o','MarkerFaceColor','b','MarkerSize',8)
axis([0 8 0 0.8])
M(1)=getframe;
dt=1/128;
for j = 2:1000
t(j)=t(j-1)+dt;
x=v0*cos(theta0)*t(j);
y=v0*sin(theta0)*t(j)-0.5*g*t(j)^2;
plot(x,y,'o','MarkerFaceColor','b','MarkerSize',8);
axis([0 8 0 0.8]);
M(j)=getframe;
if y<=0
theta0 = atan(y(j-2)/(x(j)-x(j-2)));
v0 = 0.8*v0;
plot(x(j),0,'o','MarkerFaceColor','b','MarkerSize',8)
M(j) = getframe;
end
end
pause
movie(M,1)
2 Comments
Chris
on 6 Mar 2021
I'm not entirely sure what value theta0 is meant to take when within that loop. y first turns negative when j=94, but don't forget that y is just a scalar the way you have it currently, so there's only one entry in position (1). In
theta0 = atan(y(j-2)/(x(j)-x(j-2)));
the first issue it encounters is y(j-2). At that point in the execution it becomes y(94-2) i.e. y(92) - the value of y in the 92nd column but y only has one entry/value, hence why you get that error.
Marcos Granados Flores
on 6 Mar 2021
Accepted Answer
More Answers (0)
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!