MATLAB读入并处理全球DAT格式气温数据


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  %提示运行结束

转载自:https://blog.csdn.net/darcy_vb/article/details/85917715

You may also like...