matlab批量读取目录下的文件的方法

批量处理可以提高效率,这里提供一个可以批量读取nc文件的代码:

address = 'C:\Users\Hello World!!\DESKTOP\TerraClimate_ppt\';
% Get the list of files
udir = address;
form = '*.nc';
% Get the list of station names
files = GetFiles(udir,form); 
[n,p] = size(files);

读取结果如下图,然后就可以批量循环读取即可。

下面给出一个代码:

address = 'C:\Users\Hello World!!\DESKTOP\TerraClimate_ppt\';
% Get the list of files
udir = address;
form = '*.nc';
% Get the list of station names
files = GetFiles(udir,form); 
[n,p] = size(files);

ncdisp(files(1,:));
file = files(1,:);
lon = ncread(file,'lon');
lat = ncread(file,'lat');
[lon,lat] = meshgrid(lon,lat);
sta = load('station.txt');

for k = 1:n
    time = ncread(files(k,:),'time');
    dt2 = datetime((time)*24*3600, 'ConvertFrom', 'epochtime', 'Epoch', '1900-01-01');
    [yy,mm,dd] = ymd(dt2);
    for i = 1:12
        tt(i) = time_transfer([yy(i),mm(i),dd(i)],1);
    end
    ppt = ncread(files(k,:),'ppt');
    %% load station pos
    for ii = 1:length(sta(:,1))
        for jj = 1:12
            tmax(k).rg(ii,jj) = interp2(lon,lat,ppt(:,:,jj)',sta(ii,1),sta(ii,2));
        end
    end
    disp(k)
end

temp_min = cat(2,tmax.rg);

里面涉及的函数:

function files = GetFiles(udir,form)
% files = GetFiles(udir): Gets the list of files from the directory udir
%    Generate the list of files that are needed.

if ~isempty(udir) 
    % form = strcat(udir,form);
    form = fullfile(udir,form);
end
% OK, See which files we have as form_files
d = dir(form);
% Get the names of all files in the directory
dname = {d.name};
% Get the list of file full names
files = []; % sites = [];
for i = 1:length(dname)
    tname = cell2struct(dname(i),'name');
    % sites = [sites;tname.name(4:7)];
    % tname.name = strcat(udir,tname.name);
    tname.name = fullfile(udir,tname.name);
    files = [files;tname.name];
end
 

另一个处理时间的函数见:利用matlab处理netcdf文件中time变量的格式转换问题-CSDN博客

♥欢迎点赞收藏♥

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是水怪的哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值