필터 지우기
필터 지우기

How to force a for loop to continue?

조회 수: 2 (최근 30일)
Elaheh
Elaheh 2018년 8월 2일
편집: Jan 2019년 6월 27일
Hi, I need to copy data from individual excel files from 33 participants, and paste all in one excel file. I did it for the first sheet and then for the second sheet, etc. The problem is that some of the files have 4 sheets and some have 6 sheets. Also, some of the sheets do not have data. Therefore the script stops when there is no data. How can I force it to continue and report the missing data? The following stops when data doesn't exist.
first_data = true;
for i=2:34
sheet=6;
STIMroot='C:\Users\ski\CloudStation\Zahra\dissertation\data analysis\behavioral data analysis\monolingualSTIM\';
Drop='C:\Users\ski\CloudStation\Zahra\dissertation\data analysis\behavioral data analysis\monolingualSTIM\final.xls';
STIMfile=strcat(STIMroot,num2str(i),'\',num2str(i),'.xls'); %get the STIM file
if exist(STIMfile,'file')
STIMdata = xlsread( STIMfile,sheet);
data2=STIMdata(:,3:5);
if first_data == true;
export_data = data2;
first_data = false;
else
export_data = horzcat(export_data,data2 );
end
else
warningMessage = sprintf('Warning: file does not exist:\n%s',h);
continue;
end
end
xlswrite(Drop,export_data,1);

채택된 답변

OCDER
OCDER 2018년 8월 2일
Use try/catch statements to force a loop to continue due to an unexpected error.
for j = 1:10
try
... your code...
catch
warning('found error in %dth file', j);
continue
end
... your code, if "try" codes succeed
end
  댓글 수: 3
OCDER
OCDER 2018년 8월 3일
Oh, I just meant that you can use try/catch flexibly to do different things for different function errors.
%EXAMPLE 1
try
doThis %Try this, if it fails, no fatal error
catch
continue
end
doThis2; %doThis succeeded, but if doThis2 errors, make it a fatal error.
%EXAMPLE 2
try
doThis %Try this, if it fails, no fatal error
doThis2; %If this errors, it's no longer a fatal error.
catch
continue
end
Jan
Jan 2019년 6월 27일
편집: Jan 2019년 6월 27일
Some programmers avoid continue for reasons of clarity. The code can be written without it also:
for j = 1:10
try
... your code...
... your code, if "try" codes succeed
catch ME
warning('found error in %dth file: %s', j, ME.message);
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Adding custom doc에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by