Saving FOR loop values to an array

25 次查看(过去 30 天)
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.

回答(1 个)

Torsten
Torsten 2022-4-7
编辑:Torsten 2022-4-7
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 个评论
Image Analyst
Image Analyst 2022-4-7
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).

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by