For loop only running through the first file and not all files?

1 回表示 (過去 30 日間)
jschen1
jschen1 2020 年 11 月 1 日
コメント済み: Stephen23 2020 年 11 月 2 日
Hi all,
I'm having a bit of a trouble with my nested for loops. For some background, there is a folder for each year (say 1979 - 2015), and within each year is twelve folders for each month (01-12), and within each of those subfolders is a file for each day. Below is my code:
path = '/'; %just the path to the directory
finaldata = [];
for year = 1979:2015
for month = 1:12
string_year = string(year);
string_month = sprintf('%02d',month);
filepath = path + string_year + '/' + string_month + '/';
folders = dir(filepath +'*.nc');
if ~isempty(folders)
filename = folders.name;
files = filepath + filename;
for day = 1:numel(files)
%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(year,month,day) = x;
end
end
end
end
However, whenever I run the code, it only takes the first file within each monthly folder, giving me an output of much less than one would want (it gives me 12 points per year, and I need 365). How can I tell the for loop to run through all the files and not just the first one in each folder? I believe my issue is something with these lines:
filename = folders.name;
files = filepath + filename;
for day = 1:numel(files)
Thank you!
  1 件のコメント
Stephen23
Stephen23 2020 年 11 月 2 日
Do NOT use path as a variable name, as this shadows the very important inbuilt path function:
Rather than messing around with fragile string concatenation like this:
path + string_year + '/' + string_month + '/';
you should use robust fullfile (because it is the correct tool for the job), e.g.
fullfile(mypath,string_year,string_month)

サインインしてコメントする。

採用された回答

Michael Croucher
Michael Croucher 2020 年 11 月 1 日
編集済み: Michael Croucher 2020 年 11 月 1 日
How about something like this?
path = './'; %just the path to the directory
finaldata = [];
for year = 1979:2015
for month = 1:12
string_year = string(year);
string_month = sprintf('%02d',month);
filepath = path + string_year + '/' + string_month + '/';
files = dir(filepath +'*.nc');
if ~isempty(files)
for day = 1:numel(files)
full_name = filepath + files(day).name; %This will contain the full filename of each file
%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(year,month,day) = x;
end
end
end
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by