MATLAB: How to store data extracted from multiple NetCDF into already extracted txt file and add next year data after last line of previous iteration in the same txt file.

climate datanetcdfnetcdf to swat format

%MAKE SURE THE DIRECTORY IS CHANGED TO THE DIRECTORY THAT CONTAINS THE NETCDF FILES
clear
clc
% introduction of the loop
Files=dir('*.nc');
for k=1:length(Files)
FileNames=Files(k).name;
pr=ncread(FileNames,'rainfall_amount');%name of netCDF file; 'pr' is the precip variable in the netCDF file
long=ncread(FileNames,'x'); %'longitude' is the longitude variable in the netCDF file
lat=ncread(FileNames,'y'); %'latitude' is the latitude variable in the netCDF file
for j= 716:746(lat); %1:length(lat);
for i= 328:368(long); %1:length(long);
v=pr(i,j,:); %read through all lat,longs in netCDF
outfile=sprintf('%d_%d_PCP.txt',lat(j),long(i));%name of outputfile; format is 'LATITUDE_LONGITUDE_PCP.txt'
fid=fopen(outfile,'wt');
m=1;
for i = 1:2
new(m)=v(i);
m =m+1;
data= [v];
data(isnan(data)) = -99.0 ; %cleanup in case the data is a NaN
%fprintf(fid, '18910101\n');%#write the climate data starting date to header of outfile. For example, Jan. 1, 1950 is 19500101
fprintf(fid,'%5.1f\n',data); %formatting the data for SWAT specifications
fclose(fid);
disp([outfile 'created'])%display created file
clearvars data
end
end
end
end

Best Answer

% new code to extract data from netcdf file to SWAT format text file.
data =[];
Files = dir('*.nc');
for k=1:length(Files)
FilesNames = Files(k).name;
for t=1:2
pr = ncread(FilesNames,'rainfall_amount');
long = ncread(FilesNames,'x');
lat = ncread(FilesNames,'y');
end
for j = 716:746(lat);
for i = 328:368(long);
outfile =sprintf('%d_%d_PCP.txt',lat(j),long(i));
fopen all;
v = pr(i,j,:);
data2 = (v);
data2(isnan(data2)) = -99.0;
% outfile =sprintf('%d_%d_PCP.txt',lat(j),long(i));
% fopen all;
fid = fopen(outfile,'At');
data = {data;data2};
fprintf(fid,'%5.1f\n',data2);
end
fclose all;
end
end
disp([outfile 'created'])
% original code source:
% http://dficklin.weebly.com/netcdf-to-swat-climate-input-files.html