Saving FOR loop values to an array

26 views (last 30 days)
Lukas Blake
Lukas Blake on 7 Apr 2022
Commented: Image Analyst on 7 Apr 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.

Answers (1)

Torsten
Torsten on 7 Apr 2022
Edited: Torsten on 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 Comments
Image Analyst
Image Analyst on 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).

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!