My while loop only runs once then hits an error

1 view (last 30 days)
Jordan
Jordan on 21 Oct 2023
Commented: Jordan on 21 Oct 2023
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
t = 0.0100
v = 3.1019
h = 0.0155
n = 2
Index exceeds the number of array elements. Index must not exceed 1.
grid on;
plot(t(n),h(n),'-or','MarkerFaceColor','r')
hold on;
plot(t(n),v(n),'--ob','MarkerFaceColor','b')
hold on;

Answers (1)

Torsten
Torsten on 21 Oct 2023
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 Parallel for-Loops (parfor) in Help Center and File Exchange

Tags

Products


Release

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!