Why array only saves last run of results from nested FOR Loop?
30 views (last 30 days)
Danupon Subanapong on 7 Nov 2018
Hello guys, I have been seeking for a solution for this, but I can't find it. I created a for loops and store values for each loops in array. However, the only results from last run are save to array. Could you please explain me why and how to solve it? Here is my code, it is about create a file name with a format of 'HT-yyyy-mm-dd-hh-mi.dat'. yyyy refers as year, mm is month, dd is day, hh is hour, and mi is minute. 'My guess is that the array I preallocated is redefined again in each loops, so only the last run is saved. But how to fix it I have no idea.
[yy,mm,dd] = ymd(datetime(folder_ii, 'ConvertFrom', 'datenum'));
numdays_i=(ii - Num_date_i)+1;
Thank you in advance
Stephen23 on 7 Nov 2018
Edited: Stephen23 on 8 Nov 2018
"I created a for loops..."
Yes, you did.
"...and store values for each loops in array."
No, you did not.
"Could you please explain me why..."
Because you did not use any indexing to store the output data in any array.
"...and how to solve it?"
Preallocate array/s before the loop, and within the loop use indexing to store your calculated value/s in the array/s. That is all. Here is a simple example of how to use indexing to store values in an array:
A = nan(1,4);
for k = 1:4
A(k) = sqrt(k);
Depending on the sizes of the data you want to store you might want to use a cell array or some dimensions of an array (e.g. rows of a matrix). This depends on the data sizes and classes, which you have not told us anything about.
Your variable names, e.g. folder_ii and file_name_ii with the loop variable in them, hint that you were trying to magically change the variable name in the loop. Magically accessing variable names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
The indexing that I showed you is much simpler, is less liable to bugs, and is much much more efficient. Note that the introductory tutorials show how to use loops and indexing, which is why these tutorials are recommended for all beginners (who need to learn basic MATLAB concepts):