フィルターのクリア

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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by