- 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 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Jan
il 26 Set 2013
Modificato: Jan
il 26 Set 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:
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 Commenti
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!