James
James

Reputation: 99

Matlab iterating through files in a folder, and check if the file name has specific characters

I have some climate data files (netcdf) of the same dimension.

For example: agg_humidity_bc_historical_1980_2001.nc

agg_humidity_bc_future_2020_2040.nc

agg_wind_bc_historical_1980_2001.nc

agg_precipitation_bc_future_2020_2040.nc

.....

I have a program in MATLAB to extract a specific data point from every single file. I want to iterate through all the files, check the variable name in the file name, e.g. humidity, wind, precipitation etc., and extract the data based on the variable. Then I want to store these extracted values to csv files with the same name of the nc files, like:

agg_humidity_bc_future_2020_2040.csv

agg_wind_bc_historical_1980_2001.csv

agg_precipitation_bc_future_2020_2040.csv

Here is the code I have by now.

mkdir test
data=dir('*.nc');

  for i=1:length(data)
  ncFile=data(i).name

  ??? How to check which variable is in the ncFile? 

  %%Got the index of the location of
  LonInd=22;
  LatInd=10;

  if variable=humidity
    SH=ncread(ncFile,'humidity',[LonInd, LatInd, 1], [1 1 inf]);
    SH=squeeze(SH);
    fid = fopen(['test\' ncFile.csv],'w'); 
    fprintf(fid,%d,SH)
  else if variable=wind
    wind=ncread(ncFile,'wind',[LonInd, LatInd, 1], [1 1 inf]);
    wind=squeeze(wind);
    fid = fopen(['test\' ncFile.csv],'w'); 
    fprintf(fid,%d,wind)
    fid = fclose(fid);
    fid = fclose(fid);
  else if variable=wind
    precipitation=ncread(ncFile,'precipitation',[LonInd, LatInd, 1], [1 1 inf]);
    precipitation=squeeze(precipitation);
    fid = fopen(['test\' ncFile.csv],'w'); 
    fprintf(fid,%d,precipitation)
    fid = fclose(fid);
end

Can anybody help me finish this code?

Thanks

Upvotes: 0

Views: 227

Answers (1)

Sushant Kafle
Sushant Kafle

Reputation: 446

With what I understand, ncFile contains the list of file and you want to distinguish certain file according to the file name?

If that is what you want to do them, you can do:

ncFile = data(1).name 
result = findStr(ncFile, 'desired file name') 

Then check if the result is empty or not (you can use isempty). If the result is empty, the ncFile is not what you are looking for.

Upvotes: 2

Related Questions