How can I go to the next iteration when one fails?

8 views (last 30 days)
I have a huge series of subjectfiles named data1.txt, data2.txt, data5.txt etc However, when some txtfiles are missing (here for example data3 and data4, the for loop terminates and the data is not loaded. I tried to fix this using try, catch and continue. Although the code below works to a certain degree, the problem is that not all data is loaded. It seems to stop somewhere. Does anybody know how to adapt this code in a way that all data is loaded correctly. Or maybe another example that will work? Thanks!
files = dir('*.txt');
for i = 1:length(files)
try
load (['data' num2str(i) '.txt']);
catch
i = i + 1;
load (['data' num2str(i) '.txt']);
continue;
end
end

Accepted Answer

Jan
Jan on 26 Sep 2013
Edited: Jan on 26 Sep 2013
You crate a list of existing files by the DIR command already. So there is no reasons not to use it:
folder = 'C:\Temp\'; % Adjust
files = dir(fullfile(Folder, '*.txt']);
for i = 1:length(files)
aFile = fullfile(Folder, files(i).name);
try
load(aFile);
catch
warning('Cannot find file %s', aFile);
end
end
You code contains several other problems:
  1. Increasing the loop counter i inside the loop does not work in Matlab.
  2. The continue is not required, because the loop is resumed without it also.
  3. Better check the source of the problem instead of catching a failing command:
A cleaner version:
for i = 1:length(files)
if exist(['data' num2str(i) '.txt'], 'file')
try
load (['data' num2str(i) '.txt']);
catch
% Nothing to do actually!
end
end
end
But if one file is missing, the loop will still stop at length(files). Then less than length(files) are imported. Se my above suggestion for a better solution.
Notice that loading MAT files directly into the workspace can lead to unexpected behavior and slows down Matlab. Better store the output in a variable.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!