How to direct FOR loop to next iteration when one fails - and just skip failed iteration, when compiling date in structural vectors?

I have a series of functions that compile .txt file data. Below are two functions, FUNCTION 2 calls FUNCTION 1.
The problem is, sometimes I input a range of data files to compile... and if one file is missing, the for loop terminates and the data is not compiled.
I have tried using return, or continue within the for loop, if the data vector produced is empty (e.g., file doesn't exist), to no avail.
Any ideas?
The for loop terminates here in FUNCTION 1:
for field = 1:length(allfieldnames{1}) dat.(cell2mat(allfieldnames{1}(field,:))) = alldat{field}; end
.... and terminates here in FUNCTION 2:
else
allfieldnames = fieldnames(dat);
for field = 1:length(allfieldnames)
newalldat.(allfieldnames{field}) = [alldat.(allfieldnames{field});dat.(allfieldnames{field})];
%%%%%%%%% FUNCTION 1:
function dat = td_session(filename,rat,session);
%% opens data file and assigns 'fileID' %% filename - 'DIS_F20_S14.dat.txt' dat = []; fid = fopen(filename);
%% error message for most recent failed file if fid < 0, fprintf('***Warning: could not open %s...skipping\n' ,filename), return; end %% Reads data from opened files in 'fid' % places data into matrix [data] [dattxt] = fscanf(fid,'%c',inf); allfieldnames = textscan(dattxt,'%s',15); alldat = textscan(dattxt,'%d %s %d %s %d %d %d %f %f %f %f %s %s %s %s','HeaderLines',2);
for field = 1:length(allfieldnames{1}) dat.(cell2mat(allfieldnames{1}(field,:))) = alldat{field}; end len = length(alldat{field}); dat.RatID = rat.*ones(len,1); dat.SessID = session.*ones(len,1); fclose(fid);
FUNCTION 2:
verbose = 1; DATA = []; for r = 1:length(rat) for s = 1:length(sess) if(verbose), fprintf('Sess %d, Rat %d\n',sess(s),rat(r)); end filename = cell2mat(filenames_cells{r}(s,:)); fidtest = fopen(filename), if fidtest < 0;, return, end dat = td_session(filename,rat(r),sess(s)); if ~isempty(dat), DATA = appendData(DATA,dat);
if (verbose), fprintf('Appended file %s\n',filename); end
end
if isempty(dat), continue, end
end
end
function newalldat = appendData(alldat,dat)
if isempty(alldat)
newalldat = dat;
else
allfieldnames = fieldnames(dat);
for field = 1:length(allfieldnames)
newalldat.(allfieldnames{field}) = [alldat.(allfieldnames{field});dat.(allfieldnames{field})];
end
end

1 Comment

Please use the code formatting to make your code readable. Look at the "Markup" link on this page.

Sign in to comment.

Answers (1)

Just answer the question in your title, use try() and catch() to capture the error, use continue to go to the next iteration.
for k=1:100
try
% do something
catch
continue;
end
end
To find out more
help try
help continue

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 11 Jun 2011

Community Treasure Hunt

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

Start Hunting!