필터 지우기
필터 지우기

How to continue for loop if file not found?

조회 수: 4 (최근 30일)
jschen1
jschen1 2020년 10월 31일
댓글: jschen1 2020년 11월 1일
Hi all,
I'm trying to sort through subfolders on a remote server (i.e there is a folder for each year, and within each year is 12 months, each in their own folder, and then each monthly folder has a file for each day and I am looking at those daily files). So I created some code to sort through each file, but the issue is that there is no files for two of the months. How can I tell the code to skip those years? Here is my code:
path = '/' %just the path to the directory
finaldata = NaN(37,365);
for year = 1979:2015
for month = 1:12
string_year = string(iyear);
string_month = sprintf('%02d',imonth);
filepath = path + string_year + '/' + string_month + '/';
folders = dir(file_path +'*.nc');
filename = folders.name;
files = filepath + filename;
if ~isfile(files)
continue;
end
for day = 1:length(files)
%some code on data processing
%x is output of data, which is a single number for each file and then that is put in the empty array
finaldata(month,day) = x;
end
end
end
Here is the section in question:
if ~isfile(files)
continue;
end
I keep getting an error that says "Insufficent number of outputs from the right hand sign of equal sign to satisfy argument" in reference to the line "filename = folders.name", so I don't think it is working. Thank you!
  댓글 수: 1
jschen1
jschen1 2020년 10월 31일
I also am worried I have it in the wrong location, so any insight on that would really help!

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

채택된 답변

Adam Danz
Adam Danz 2020년 10월 31일
편집: Adam Danz 2020년 10월 31일
First, "file_path" should be filepath to match the pre-defined variable name 3 lines above.
Second, if the filepath does not exist, folders will be empty,
folders = dir(filepath +'*.nc');
so a better test would be,
folders = dir(file_path +'*.nc');
if ~isempty(folders) % <---test
filename = folders.name;
files = filepath + filename;
for day = 1:numel(files) % <--- use numel instead of length
% [ STUFF ]
end
end
Make sure you're preallocating any loop variables in case iterations are skipped!
  댓글 수: 1
jschen1
jschen1 2020년 11월 1일
Thank you so much Adam, this worked perfect!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by