Why array only saves last run of results from nested FOR Loop?

12 views (last 30 days)
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.
Date_matrix=strings(No_of_file_1D,1,numdays);
for ii=Num_date_i:Num_date_j
folder_ii=datestr(ii,'yyyy-mm-dd');
[yy,mm,dd] = ymd(datetime(folder_ii, 'ConvertFrom', 'datenum'));
numdays_i=(ii - Num_date_i)+1;
for hh=0:1:24
hh_i=hh;
for mi=10:10:60
mi_i=mi;
index_save=(numdays_i)*No_of_file_1D+hh*(60/Time_interval)+(mi)/10;
if mi==60
mi_i=0;
hh_i=hh+1;
else
end
if hh==24
hh_i=00;
dd=dd+1;
else
end
file_name_ii=sprintf('%s%04d%c%02d%c%02d%c%02d%c%02d%s','HT-',yy,'-',mm,'-',...
dd,'-',hh_i,'-',mi_i,'.dat');
Date_matrix(index_save,1,numdays_i)=file_name_ii;
end
end
end
Thank you in advance

Accepted Answer

Stephen23
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);
end
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):

More Answers (0)

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!