MATLAB: Loop in all scripts

analysisfor looploop

Hi all,
I have a GUI that needs to loop through a certain amount of files (depends on the user selection). The files are loaded with this code:
FNM = handles.FNM;
Filenames = handles.Filenames;
for k = 1:length(FNM)
current = FNM {k};
kstr = num2str(k);
amountFilesstr = num2str(length(FNM));
baseFileName = Filenames(k).name;
fullfilename = fullfile(foldername, baseFileName);
Currentfiletest = ['Now loading file ' kstr ' of ' amountFilesstr ' ' '(' current ')'];
data = readtable(fullfilename);
set(handles.figure1, 'pointer', 'watch');
drawnow;
set(handles.figure1, 'pointer', oldpointer);
set(handles.text7, 'string', Currentfiletest);
drawnow
handles.data = data;
complete = ['Files have been loaded'];
set(handles.text7, 'string', complete);
end
This is done in pushbutton1
Now, pushbutton 2 should do the analyses on all these files. I am using the following code:
if get(handles.specfiles, 'value') == 1
FNM = handles.FNM;
for i = 1:length(FNM)
ReadData
WorkTimeSpec
AwakeTimeSpec
NonWearAwakeSpec
NonWearWorkSpec
assignin('base', 'Data', Data)
if get(handles.diaryawake, 'value') == 0 && get(handles.checkbox12, 'value') == 0 &&...
get(handles.checkbox10, 'value') == 0 && get(handles.validdays, 'value') == 0 &&...
get(handles.checkbox31, 'value') == 0
Data = TimevCounts;
end
NonWearTime
ValidWearTime
SplitValidData
CutoffPoint
Bouts
Breaks
end
I am new to matlab and have no experience with for loops but I thought this is the way to do it. However, the data does not add up and I cannot seem to figure out why..
Hope anyone can help me

Best Answer

This line of code inside the loop:
handles.data = data;
completely replaces the field data on each loop iteration: on the second iteration it completely replaces whatever was allocated during the first iteration, on the third it replaces what was allocated on the second, etc. So at the end you only have the last iterations's data. If you want to save the data from each iteration, then do something like this:
handles.data = cell(1,numel(FNM));
for k = 1:numel(FNM)
...
handles.data{k} = data;
...
end
See also: