- Increasing the loop counter i inside the loop does not work in Matlab.
- The continue is not required, because the loop is resumed without it also.
- Better check the source of the problem instead of catching a failing command:
How can I go to the next iteration when one fails?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
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:
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!