clc
clear
% 讀入.dat文件到變量temp_month
temp_month=dlmread('F:\GIS\yuan\cru_ts4.02.2001.2010.tmp.dat'); % dlmread function read ASCII-delimited file of numeric data into matrix
% 將二維矩陣temp_month(43200*720)升爲三維矩陣temp_year_3d(4320*720*10)
temp_year2=mat2cell(temp_month,[4320 4320 4320 4320 4320 4320 4320 4320 4320 4320],[720]); %10個4320,表示10年
temp_year_3d=cat(3,temp_year2{:});
[rows,columns,pages]=size(temp_year_3d); %返回三維矩陣行、列、頁數
% 對三維矩陣temp_year_3d(4320*720*10)的每一頁拆分成360*720*12大小並求各頁平均,得到全球0.5°逐年年均溫網格
for page=1:pages
temp_month2=mat2cell(temp_year_3d(:,:,page),[360 360 360 360 360 360 360 360 360 360 360 360],[720]); %12個360,表示12個月
temp_month_3d=cat(3,temp_month2{:});
temp_year(:,:,page)=mean(temp_month_3d,3); %temp_year(:,:,:)爲全球1901~1910年逐年平均氣溫ASCII數據
end
% *************讀新的數據時修改以下代碼 num2str(page+1900)****************************
% 將二維數組temp_year(:,:,page)(360*720)分別寫入1901.txt,1902.txt,1903.txt...
for page=1:pages
str=['F:/GIS/yuan/globe_temp/' num2str(page+2000) '.txt'] % num2str(page+1900)前後都要空一格
fid=fopen(str,'wt');
%% 插入文件頭
fprintf(fid,'%s\n','ncols 720');
fprintf(fid,'%s\n','nrows 360');
fprintf(fid,'%s\n','xllcorner -180.00');
fprintf(fid,'%s\n','yllcorner -90.00');
fprintf(fid,'%s\n','cellsize 0.50');
fprintf(fid,'%s\n','NODATA_value -999');
%% 寫入數據
input=flipud(temp_year(:,:,page)); % 注意這裏要用到flipud()函數,將數組上下顛倒,這樣根據文件頭讀入的數據纔是對的,另外再次印證MATLAB真的很強大
[row_temp,col_temp]=size(input);
for row=1:row_temp
for col=1:col_temp
if col==col_temp
fprintf(fid,'%g\n',input(row,col));
else
fprintf(fid,'%g\t',input(row,col));
end
end
end
fclose(fid);
end
figure %提示運行結束
MATLAB讀入並處理全球DAT格式氣溫數據
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.