How to continue for loop if file not found?

6 views (last 30 days)
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 Comment
jschen1
jschen1 on 31 Oct 2020
I also am worried I have it in the wrong location, so any insight on that would really help!

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 31 Oct 2020
Edited: Adam Danz on 31 Oct 2020
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!

More Answers (0)

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!