My while loop only runs once then hits an error

2 visualizaciones (últimos 30 días)
Jordan
Jordan el 21 de Oct. de 2023
Comentada: Jordan el 21 de Oct. de 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;

Respuestas (1)

Torsten
Torsten el 21 de Oct. de 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;

Categorías

Más información sobre Parallel for-Loops (parfor) en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by