Index exceeds the number of array elements (2).
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hello everyone, I am new to MatLab and working on a code...
When i implent if statement in my for loop I get "Index exceeds the number of array elements (2)" error.
Would appreciate any help.
Line 39 if M(n) > mass_r;
% first we define all variables
total_t = 3600; % Time lenght S
dt = 1; % Time step S
t = 0:dt:total_t;
dt = 0.1; % Time step S
V0 = 0; % Initial x velocity m/s
x = 0; % Initial x position
y = 0; % Initial y position
mass_r = 54000; % Mass of Empty Rocket Kg
mass_f = 840000; % Proppelant Mass Kg
M = (mass_f+mass_r); % Total Mass: Proppelant+Empty Rocket Mass kg
mass_e = 5.9722*10^24; % Earth Mass in Kg
Cd = 0.4; % Coefficient of Drag
Ve = 4500; % Exhaust gasses velocity (Constant)
A = 75; % Cross-sectional area of the rocket
dm = 5000; % Mass rate change kg/s
dm0 = 0; % Rate of change after fuel burnt
G = 6.67408*10^-11; % Gravitaional Constant
R = 6371; % Radius of Earth Km
Ang = 0; %Initial angel of launch
p = 1.225; % For test purpose assume density is constand (Change at a later stage of code development!)
rad = pi*Ang/180;
%-------------------------------------------------------------------------
xc = zeros(1,total_t);
yc = zeros(1,total_t);
V=zeros(1,length(total_t));
V(1) = V0
x(1) = 0
y(1) = 0
V(1) = V0
M(1) = mass_f+mass_r;
M(2) = mass_f-dm;
for n=2:length(t)
if M(n) > mass_r;
M(n)=M(n-1)-dm*dt;
else
M(n)=0;
end
end
%%V(n) = -(A*Cd*p*dt*(V(1)^2)+2*dt*G(mass_e*M(n)/R^2)-2*dm*Ve/2*M(n))
%%V(n) = (Ve*(dm/dt)/M(n-1)*dt)-((G((mass_e*M(n-1))/(R^2)))/M(n)*dt)-((0.5*p*A*V^2*CD)/M(n-1)*dt);
%%V(n) = -(A*Cd*p*dt*(V(1)^2)+2*dt*G(mass_e*M(n)/R^2)-2*dm*Ve/2*M(n))
%%V(n) = (Ve*(dm/dt)/M(n-1)*dt)-((G((mass_e*M(n-1))/(R^2)))/M(n)*dt)-((0.5*p*A*V^2*CD)/M(n-1)*
plot(t,M)
2 Commenti
Ankit
il 27 Mar 2020
this problem is due to the different size of the vector.
size of M is 2 and your for loop run from 2 to 3601 (length of vector time "t")
M(1) = 894000, M(2) = 893500; M(3) .... M(3601) -- you need to define in order to execute the loop correctly
Risposta accettata
Guillaume
il 27 Mar 2020
Always preallocate vectors instead of growing them in a loop, so before the loop:
M = zeros(1, total_t);
While this will get rid of the error it won't change the fact that for all n > 2 you're checking the M(n) value before you've actually put something into M(n). There's clearly something wrong with the logic of your loop.
Also, spot the difference:
xc = zeros(1,total_t);
yc = zeros(1,total_t);
V=zeros(1,length(total_t));
length(total_t) is 1, so V is a scalar.
Also, spot the repetition:
V(1) = V0
x(1) = 0
y(1) = 0
V(1) = V0
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!