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

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.

Answers (2)

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 on 16 Oct 2017
Edited: Cedric on 16 Oct 2017
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 Comments

I'm really trying to debug this thing. It looks so simple. For the sake of clarity, I will post the entire section of code, in it's current version. This is part of a M/M/1 queuing simulation. Data is provided in the 2 txt files, and must be programmatically incorporated into the code. Those files each contain 300 rows x 1 column of numbers. The import works fine, and the data is correct when checking those import variables. Ai is a variable representing data that is changed in each iteration, and needs to have all 300 values stored in the order they are updated, to be used for calculations further down. Maybe I need a break from it, and fresh eyes can see clearly.
ia_time = importdata('Data1.txt');
svc_time = importdata('Data2.txt');
arrival = 0;
Ai = 0;
Di = 0;
WQi = 0;
Ti = 0;
for i = 1:300
if arrival <1
Ai(i) = Ai(i) + ia_time(i);
else
arrival = ia_time(i-1);
Ai = ia_time(i) + arrival;
end
disp(Ai);
Ti = max(Ai,Di-1);
WQi = Ti-Ai;
Di = Ti+svc_time;
end
The code in the question is puzzling on many levels.
First, the comment on this line:
disp(Ai); % <-- displays all 20 values
is misleading. It does not displays all 20 values. It displays the current value of Ai on the current step of the loop. At any point in the code, Ai only ever contains one value.
This is where it gets puzzling: It looks like you expected Ai (or maybe A) to be a vector of 20 values. In which case, as Cedric has answered, you should have used A(i) (or Ai(i) !) but then would have already created that variable with 20 values before the loop since you're intending to add to each of these elements within your loop. But if you had declared that variable as a vector, you wouldn't be saying that disp is ever showing the correct value...
In addition, assuming you meant A(i) then the line
A(i) = A(i) + ia_time(i)
only adds a value once to each element of A(i), and that value does not depend on previous iterations. The only way your faulty code could have displayed all 20 correct values would thus be if all A(i) values were 0, in which case the above line is pointless and:
A(i) = ia_time(i)
would be simpler.
Apparently Ai is not meant to be a vector (?) It would be simpler if you told us what you want to achieve, because we cannot easily guess it from the code.
I've got a feeling that somewhere the code is meant to have a
A(i+1) = A(i) + ...
otherwise the loop makes absolutely no sense at all.
I would not bet against that feeling ;)
Guillaume, you are correct - I misspoke earlier. The values were displayed correctly for Ai, as they popped up in each loop. My headache is that I can't figure out why each value is not being stored during each loop. I am sure it is obvious, but I am a novice with coding, especially in Matlab. For clarity, I posted the whole section of code in a previous reply.
But what do you want to achieve? Is Ai meant to grow?
'ia_time' contains 300 rows of data that it reads from Data1.txt. So the loop defines 'i' to be the current value from 1-300. As the loop iterates, it reads the next value of 'ia_time'. This value is then added to the previous value of 'Ai', creating a new current value of 'Ai'. To get the first value for 'Ai', it would simply be 'ia_time'+0. However, this gave an error that indices must be positive or logicals. This is why I added the if-else and the 'arrival' variable. This way, I can get past the first iteration, and continue adding the current 'ia_time' to the previous 'Ai', until i=300. From this process I should end up with a separate 300,1 array of values for both 'ia_time' (which is just the original txt file data), and a 300,1 array of values for 'Ai', which has just been calculated.
It's a complex, yet easy issue. Looking back over it now, I'm not sure how I ended up where I did. I'm going to scrap it all, and start from scratch.
Is the following doing what you were trying to achieve?
ia_time = importdata('Data1.txt') ;
Ai = cumsum( is_time ) ;
If not, could you give e.g. the first 5 values of ia_time and the first 5 values of Ai as you would like them to be?
I've solved my first issue. Now I just have to get the others to play nice. It may not be elegant, but the Ai variable seems to work for now.
for i = 1:300
if i-1 < 1
Ai(i) = ia_time(i) + 0;
else Ai(i) = ia_time(i) + Ai(i-1);
end
end
I've clipped a sample from my Excel sheet. It's so easy to do there, I wish it was as such in Matlab. I guess it will be, once I practice it a bit more.
Well, as we've both shown it's so easy easy to do in matlab as well:
A = cumsum(ia_time);
Note that
if i-1 < 1
is needlessly complicated
if i < 2
or even simpler
if i == 1
Similarly, what is the point of + 0 ?
See my answer for the proper way to write it as a loop. But use cumsum
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
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.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Asked:

on 16 Oct 2017

Commented:

on 5 Apr 2022

Community Treasure Hunt

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

Start Hunting!