How do I properly append to an array within a loop?

532 ビュー (過去 30 日間)
Loren Graf
Loren Graf 2017 年 10 月 16 日
コメント済み: Luke Calabretta 2022 年 4 月 5 日
I am running a loop of 300 iterations. Within the loop, I have a logic statement as follows.
for i = 1:300
if arrival <1
Ai = Ai + ia_time(i);
else
arrival = ia_time(i-1);
Ai = ia_time(i) + arrival;
end
disp(Ai); % <-- displays all values
end
disp(Ai); % <-- only displays the final value from the loop
While the loop is open, 'disp(Ai)' prints the values correctly. However, if I attempt to use or print the variable after the final closing 'end', I only get the one final value of Ai. What I would like is an array of all values that I can reuse for future operations later in the code. I feel like it is not creating the array properly, and perhaps I need to assign the value of Ai to another variable as the loop iterates, but I can't seem to make that work either.
I know this should be simple, but I am beating my newbie head on the desk.
  2 件のコメント
per isakson
per isakson 2017 年 10 月 16 日
Replace
Ai =
by
Ai(i) =
Luke Calabretta
Luke Calabretta 2022 年 4 月 5 日
Thank you!

サインインしてコメントする。

回答 (2 件)

Guillaume
Guillaume 2017 年 10 月 16 日
If all you're trying to do is accumulate the values of ia_time, then
A = cumsum(ia_time);
If you really wanted to use a loop for that:
A = zeros(size(ia_time));
A(1) = ia_time(1);
for i = 2:numel(ia_time) %never hardcode end values, ask for what it actually is
A(i) = A(i-1) + ia_time(i);
end

Cedric
Cedric 2017 年 10 月 16 日
編集済み: Cedric 2017 年 10 月 16 日
You shouldn't name your variable Ai if i is meant to be the index. Assuming that A is already defined and that, at loop index i, you want to alter its component at position/index i:
A(i) = A(i) + ia_time(i) ;
which is: add element i of vector ia_time to element i of A, and store the result back in A at position i.
  13 件のコメント
Cedric
Cedric 2017 年 10 月 16 日
編集済み: Cedric 2017 年 10 月 16 日
Looking at your PDF, those i mean "associated with the index". Try to precompute A, preallocate the others, initialize all, and loop the way Guillaume proposes:
ia_time = importdata('Data1.txt');
svc_time = importdata('Data2.txt');
A = cumsum( ia_time ) ;
T = zeros( size( A )) ;
WQ = zeros( size( A )) ;
D = zeros( size( A )) ;
T(1) = .. ?
WQ(1) = .. ?
D(1) = .. ?
for i = 2 : length( A )
T(i) = ... ?
WQ(i) = ... ?
D(i) = ... ?
end
Loren Graf
Loren Graf 2017 年 10 月 17 日
Thank you for your input earlier. Unfortunately, I had to go to work. When I looked at it later, I noticed several parts that made me slap myself in the forehead. Indeed, I over-complicated some of the inputs. It is amazing how a tired brain sometimes cannot make sense of easy issues.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by