Saving FOR loop values to an array

26 vues (au cours des 30 derniers jours)
Lukas Blake
Lukas Blake le 7 Avr 2022
Commenté : Image Analyst le 7 Avr 2022
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.

Réponses (1)

Torsten
Torsten le 7 Avr 2022
Modifié(e) : Torsten le 7 Avr 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 commentaires
Lukas Blake
Lukas Blake le 7 Avr 2022
Works perfectly. Thanks
Image Analyst
Image Analyst le 7 Avr 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).

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by