五组数据求对应月份的平均值代码
% Set the folders for GPP raster data
folder1 = 'J:\third\3gpp\1982-2018Gpp\FLUX_GPP';
folder2 = 'J:\third\3gpp\1982-2018Gpp\GLASS_GPP';
folder3 = 'J:\third\3gpp\1982-2018Gpp\GPP3';
folder4 = 'J:\third\3gpp\1982-2018Gpp\GPP4';
folder5 = 'J:\third\3gpp\1982-2018Gpp\GPP5';
% Set the output folder
outputFolder = 'J:\third\3gpp\1982-2018Gpp\meangpp';
% Get a list of files in each directory
files1 = dir(fullfile(folder1, '*.tif')); % Assuming the files are GeoTIFFs
files2 = dir(fullfile(folder2, '*.tif'));
files3 = dir(fullfile(folder3, '*.tif'));
files4 = dir(fullfile(folder4, '*.tif'));
files5 = dir(fullfile(folder5, '*.tif'));
% Convert to lists of filenames
files1_names = {files1.name};
files2_names = {files2.name};
files3_names = {files3.name};
files4_names = {files4.name};
files5_names = {files5.name};
% Find common files across the five sets
common_files = intersect(intersect(intersect(intersect(files1_names, files2_names), files3_names), files4_names), files5_names);
% Ensure the output folder exists
if ~exist(outputFolder, 'dir')
mkdir(outputFolder)
end
% Process each common file
for i = 1:length(common_files)
filename = common_files{i};
% Build the full path for each file
file1 = fullfile(folder1, filename);
file2 = fullfile(folder2, filename);
file3 = fullfile(folder3, filename);
file4 = fullfile(folder4, filename);
file5 = fullfile(folder5, filename);
% Read each file's data
[data1, R1] = geotiffread(file1);
[data2, R2] = geotiffread(file2);
[data3, R3] = geotiffread(file3);
[data4, R4] = geotiffread(file4);
[data5, R5] = geotiffread(file5);
% Check that the spatial references are the same
if ~isequal(R1, R2) || ~isequal(R1, R3) || ~isequal(R1, R4) || ~isequal(R1, R5)
error('Spatial references do not match for the files.');
end
% Convert input data to double for calculations
data1 = double(data1);
data2 = double(data2);
data3 = double(data3);
data4 = double(data4);
data5 = double(data5);
% Filter for valid values (greater or equal to 0 AND less or equal to 10000)
data1(data1 < 0 | data1 > 10000) = NaN;
data2(data2 < 0 | data2 > 10000) = NaN;
data3(data3 < 0 | data3 > 10000) = NaN;
data4(data4 < 0 | data4 > 10000) = NaN;
data5(data5 < 0 | data5 > 10000) = NaN;
% Calculate average values only for valid values
% Note: If all values at a position are NaN, the result will be NaN
validIndices = ~isnan(data1) & ~isnan(data2) & ~isnan(data3) & ~isnan(data4) & ~isnan(data5);
average_data = nan(size(data1)); % Initialize the average array with NaNs
average_data(validIndices) = (data1(validIndices) + data2(validIndices) + data3(validIndices) + data4(validIndices) + data5(validIndices)) / 5;
% Write the new raster to the output folder
outputFilename = fullfile(outputFolder, filename);
geotiffwrite(outputFilename, average_data, R1);
end
fprintf('Processing complete. Averaged rasters are saved in %s\n', outputFolder);