input_path = 'E:\LAI\GLASS_LAI\IWEMS_LAI\8118x\'; output_path = 'E:\LAI\GLASS_LAI\IWEMS_LAI\8118s\'; output_file_prefix = 'output_'; % 定义时间序列 start_date = datetime('1981-01-01'); end_date = datetime('1981-12-31'); date_range = start_date:hours(1):end_date; % 循环处理每个tif文件 for i = 1:46 % 读取tif文件 filepath = fullfile(input_path','*.tif'); raster = geotiffread(filepath); info = geotiffinfo(filepath); % 将栅格数据转换为时间序列 ts = timeseries(raster, date_range); % 插值为每小时一张的数据 ts_hourly = resample(ts, date_range, 'linear'); % 将时间序列转换为栅格数据 raster_hourly = reshape(ts_hourly.Data, [size(raster, 1), size(raster, 2), numel(date_range)]); % 导出为tif文件 output_filename = [output_file_prefix, filename]; output_filepath = fullfile(output_path, output_filename); geotiffwrite(output_filepath, raster_hourly, info); end请优化上面代码
时间: 2024-03-11 14:43:35 浏览: 16
下面是优化后的代码:
```
input_path = 'E:\LAI\GLASS_LAI\IWEMS_LAI\8118x\';
output_path = 'E:\LAI\GLASS_LAI\IWEMS_LAI\8118s\';
output_file_prefix = 'output_';
% 定义时间序列
start_date = datetime('1981-01-01');
end_date = datetime('1981-12-31');
date_range = start_date:hours(1):end_date;
% 获取所有tif文件的路径
tifs = dir(fullfile(input_path, '*.tif'));
% 循环处理每个tif文件
for i = 1:length(tifs)
% 读取tif文件
filepath = fullfile(input_path, tifs(i).name);
raster = geotiffread(filepath);
info = geotiffinfo(filepath);
% 将栅格数据转换为时间序列
ts = timeseries(raster, date_range);
% 插值为每小时一张的数据
ts_hourly = resample(ts, date_range, 'linear');
% 将时间序列转换为栅格数据
raster_hourly = reshape(ts_hourly.Data, [size(raster, 1), size(raster, 2), numel(date_range)]);
% 导出为tif文件
output_filename = [output_file_prefix, tifs(i).name];
output_filepath = fullfile(output_path, output_filename);
geotiffwrite(output_filepath, raster_hourly, info);
end
```
优化说明:
1. 获取所有tif文件的路径,使用 `dir` 函数来实现,避免了重复获取文件路径的代码。
2. `filepath` 的生成方式更改,使用 `tifs(i).name` 来获取文件名。
3. 增加了 `length` 函数来获取文件个数,避免了写死循环次数的问题。
4. 优化了代码的缩进,增加了代码的可读性。