Info

This question is closed. Reopen it to edit or answer.

Loop filename substitution i.e. loop for Year2002_month01.nc for varying year and month.

1 view (last 30 days)
Can anyone help me with this, I have created a script in MatLab which will process a set of data for me in a specific way and produce output images. I've been able to run simple loops for values but I have never carried out a similar process for varying input filenames.
I'm wondering whether it is possible to do a substitution style loop to run the script on a large amount of files based on the start filename.
Say for example I had the following files: - year01_month01 - year01_month02 - ... - year02_month01 - ..
I want the loop to loop for all the month files for year 1 then go on to year 2, until all files in the directory are processed, or alternatively I could set the final year and month. I saw a similar substitution done using a method similar to for year??_month?? in UNIX, but I would need it for both variables and likewise to work in MatLab.
Hope someone can help.

Answers (1)

Walter Roberson
Walter Roberson on 29 Jun 2012
Is the 'month01' intended to be literally the word 'month' followed by a two-digit month number in the year, or is it intended to be a month name? If it is the literal word 'month' etc., then sort() applied to the filenames should work well to get the right order; if it is a month name, then a month-name sort takes a slight bit more code (and the easiest way to do that might be by a datenum() conversion)
  2 Comments
Joshua
Joshua on 29 Jun 2012
N01_1996m01T_shelf_n3.nc <--that's an example filename, the variables are the year which is in this case 1996, and the month, which is in this case 01.
I basically need it to run for years between 1993 and 2007 and months from 01 to 12. Does that make sense?
Walter Roberson
Walter Roberson on 29 Jun 2012
dirinfo = dir('N01*.nc');
filedates = regexprep({dirinfo.filename}, '^....(\d\d\d\d).(\d\d).*$', '$1$2');
[sorteddates, sortidx] = sort(filedates);
dirinfo = dirinfo(sortidx); %and then it will be in sorted order
Now
for K = 1 : length(dirinfo)
thisfile = dirinfo(K).filename;
Process file "thisfile"
end

Products

Community Treasure Hunt

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

Start Hunting!