My while loop only runs once then hits an error
Show older comments
I'm trying to get a while loop done for an assignement but my loop runs once then hits an error saying my index cant exceed 1
% Section 1
clear; clc;
n=1;
h(n) = 0;
v(n) = 0;
t(n) = 0; % initial values
m = 0.5; % mass of rocket
g = 9.81; % force of gravity
tEngineCut = 0.15; % time at wchich engine shuts off
fThrust = 160; % force of engine
a1 = (fThrust-m*g)/m; % acceleration
vChute = -20;
Dt = 0.01; % time increment in seconds
while t(n) <= tEngineCut && n<15
t(n) = t(n)+Dt
% adds Dt and t on every pass of the loop
v(n) = a1.*t(n)
% calculates the new velocity for every pass of the loop
h(n) = (1/2).*a1.*t(n)^2
n = n + 1
%calculates new height for every pass of the loop
end
grid on;
plot(t(n),h(n),'-or','MarkerFaceColor','r')
hold on;
plot(t(n),v(n),'--ob','MarkerFaceColor','b')
hold on;
Answers (1)
Maybe like this ?
% Section 1
clear; clc;
n=1;
h(n) = 0;
v(n) = 0;
t(n) = 0; % initial values
m = 0.5; % mass of rocket
g = 9.81; % force of gravity
tEngineCut = 0.15; % time at wchich engine shuts off
fThrust = 160; % force of engine
a1 = (fThrust-m*g)/m; % acceleration
vChute = -20;
Dt = 0.01; % time increment in seconds
while t(n) <= tEngineCut && n<15
t(n+1) = t(n)+Dt ;
% adds Dt and t on every pass of the loop
v(n+1) = a1.*t(n+1);
% calculates the new velocity for every pass of the loop
h(n+1) = (1/2).*a1.*t(n+1)^2;
n = n + 1;
%calculates new height for every pass of the loop
end
grid on;
plot(t,h,'-or','MarkerFaceColor','r')
hold on;
plot(t,v,'--ob','MarkerFaceColor','b')
hold on;
Categories
Find more on Creating and Concatenating Matrices 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!