12个月降水量数据逐像元相加得年数据代码,逐年输出。同样适用于需要求和的类型数据
% 修改为你的文件夹路径
inputFolderPath = 'J:\1901-2022pre';
outputFolderPath = 'J:\pre';
% 导入纬度数据
[aa, R] = geotiffread(fullfile(inputFolderPath, 'pre_1982_01.tif'));
info = geotiffinfo(fullfile(inputFolderPath, 'pre_1982_01.tif'));
% 定义年份范围
startYear = 1982;
endYear = 2021;
years = startYear:endYear;
% 初始化一个结构数组来存储每年的合成结果
annualSumPrecipitation = struct();
% 循环遍历每一年
for year = years
% 初始化一个矩阵用于存储每年的总降水
totalPrecipitation = [];
R = [];
% 循环遍历每个月
for month = 1:12
% 构造文件名
fileName = sprintf('pre_%d_%02d.tif', year, month);
filePath = fullfile(inputFolderPath, fileName);
% 检查文件是否存在
if isfile(filePath)
% 读取栅格数据
[monthlyData, R] = geotiffread(filePath);
% 如果monthlyData包含NaN或Inf值,则将它们替换为0
monthlyData(~isfinite(monthlyData)) = 0;
% 如果totalPrecipitation为空,则初始化它
if isempty(totalPrecipitation)
totalPrecipitation = zeros(size(monthlyData));
end
% 对应像元相加
totalPrecipitation = totalPrecipitation + monthlyData;
else
fprintf('File %s does not exist.\n', filePath);
end
end
% 将每年的合成结果存储在结构数组中
annualSumPrecipitation(year - startYear + 1).year = year;
annualSumPrecipitation(year - startYear + 1).totalPrecipitation = totalPrecipitation;
% 保存每年的合成结果为新的tif文件
outputFileName = sprintf('yearsum_%d_precipitation.tif', year);
outputFilePath = fullfile(outputFolderPath, outputFileName);
geotiffwrite(outputFilePath, totalPrecipitation, R);
fprintf('Year %d processed and saved to %s\n', year, outputFilePath);
end