sprintf in a for loop

Hi :) I'm having trouble creating a for loop for importing a series of netcdf files in Matlab. The only thing that changes each time is the number on the month for each of the 12 datasets, but when I run the loop, it puts the names of the datasets together so won't import them. Here's what I have been using:
A=1:12
for i=1:12
formatspec='filename-month%d-year.nc'
B=(sprintf(formatspec,A))
E=ncread(B,'netcdf_variable')
end
However, when I run this, it comes up with "could not open filename-month1-year.ncfilename-month2-year.ncfilename-month3-year.nc..." etc. Any help would be greatly appreciated, thanks!!

Réponses (1)

Image Analyst
Image Analyst le 13 Oct 2018

0 votes

Try this:
A=1:12
for i=1:12
fileName = sprintf('filename-month%d-year.nc', A(i));
E = ncread(fileName,'netcdf_variable')
end

4 commentaires

Faith
Faith le 13 Oct 2018
Great thank you!! It works now!
Faith
Faith le 13 Oct 2018
Hi, I was wondering whether you would know how to give each filename a different name in matlab as I can't analyse the individual datasets further as 'E' becomes month12 so although the previous months get imported, I can't analyse them further. Thanks again for any help!
Image Analyst
Image Analyst le 13 Oct 2018
I'd use the one in the FAQ that uses dir(). That way you get only files known to exist.
Then you process/analyze E in the loop and store the results somewhere, like in an Excel workbook or text file.
Faith
Faith le 13 Oct 2018
Okay great thank you!

Connectez-vous pour commenter.

Question posée :

le 13 Oct 2018

Commenté :

le 13 Oct 2018

Community Treasure Hunt

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

Start Hunting!

Translated by