フィルターのクリア

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

1 回表示 (過去 30 日間)
Marty Dutch
Marty Dutch 2013 年 9 月 26 日
編集済み: Jan 2013 年 9 月 26 日
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

採用された回答

Jan
Jan 2013 年 9 月 26 日
編集済み: Jan 2013 年 9 月 26 日
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.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by