Saving FOR loop values to an array
25 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hello, I'm relatively new to MATLAB and having difficulty taking a value generated by a for loop and saving that to one spot in an array. What I want to do is save the result of the variable after each iteration of the for loop to a different point in the array. The code is designed to calculate the mass of a rocket as it burns fuel, and the BurnTime and resolution variables are there so the loop gives outputs from 0 to 2 seconds at 0.1 second intervals. I have been able to get each individual value of CurrentMass to display in the command window (also included in the code here) but whenever I try to save them to the array it says "array indices must be positive integers or logical statements".
BurnTime = 2;
resolution = 0.1;
for t = 0:resolution:BurnTime
BurnRate = (-(MFuel)/BurnTime);
CurrentMass = (MRocket + MFuel) + (BurnRate * t);
Drag = 0.6 * (CurrentVelocity)^2;
Acceleration = ((Thrust - CurrentMass) + (Gravity + Drag))/CurrentMass;
CurrentVelocity = PreviousVelocity + t * Acceleration;
CurrentHeight = CurrentVelocity * t;
massArray(t) = CurrentMass;
fprintf("\n \tFor t = %.2f \n", t); %output mass calculation
fprintf("\tCurrent Mass : %.2f \n", CurrentMass);
end
Thanks in advance for any help.
0 Commenti
Risposte (1)
Torsten
il 7 Apr 2022
Modificato: Torsten
il 7 Apr 2022
T = 0:resolution:BurnTime;
nt = numel(T);
for i = 1:nt
t = T(i);
BurnRate = (-(MFuel)/BurnTime);
CurrentMass = (MRocket + MFuel) + (BurnRate * t);
Drag = 0.6 * (CurrentVelocity)^2;
Acceleration = ((Thrust - CurrentMass) + (Gravity + Drag))/CurrentMass;
CurrentVelocity = PreviousVelocity + t * Acceleration;
CurrentHeight = CurrentVelocity * t;
massArray(i) = CurrentMass;
fprintf("\n \tFor t = %.2f \n", t); %output mass calculation
fprintf("\tCurrent Mass : %.2f \n", CurrentMass);
end
2 Commenti
Image Analyst
il 7 Apr 2022
You might want to use k instead of i. We usually recommend not to use i or j to avoid confusion with the imaginary constant sqrt(-1).
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices 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!