Saving FOR loop values to an array

25 ビュー (過去 30 日間)
Lukas Blake
Lukas Blake 2022 年 4 月 7 日
コメント済み: Image Analyst 2022 年 4 月 7 日
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 件のコメント
Lukas Blake
Lukas Blake 2022 年 4 月 7 日
Works perfectly. Thanks
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 Center および File ExchangeCreating 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