我编写了一个MATLAB代码,用于从SAC(地震)文件(通过另一个代码读取)中查找地震信号(例如P波)。这个算法被称为STA/LTA触发算法(实际上对我的问题并不那么重要)
重要的是,实际上这段代码运行良好,但由于我的地震文件太大(1GB,这是两个月),执行需要将近 40 分钟才能看到结果。因此,我觉得有必要优化代码。
我听说用高级函数替换循环会有所帮助,但由于我是 MATLAB 的新手,我无法了解如何做到这一点,因为代码的目的是扫描每个时间序列。另外,我听说预分配可能会有所帮助,但我对如何实际执行此操作只有想法。
由于此代码是关于地震学的,因此可能很难理解,但我在顶部的注释可能会有所帮助。我希望我能在这里得到有用的建议。以下是我的代码。
function[pstime]=classic_LR(tseries,ltw,stw,thresh,dt)
% This is the code for "Classic LR" algorithm
% 'ns' is the number of measurement in STW-used to calculate STA
% 'nl' is the number of measurement in LTW-used to calculate LTA
% 'dt' is the time gap between measurements i.e. 0.008s for HHZ and 0.02s for BHZ
% 'ltw' and 'stw' are long and short time windows respectively
% 'lta' and 'sta' are long and short time windows average respectively
% 'sra' is the ratio between 'sta' and 'lta' which will be each component
% for a vector containing the ratio for each measurement point 'i'
% Index 'i' denotes each measurement point and this will be converted to actual time
nl=fix(ltw/dt);
ns=fix(stw/dt);
nt=length(tseries);
aseries=abs(detrend(tseries));
sra=zeros(1,nt);
for i=1:nt-ns
if i>nl
lta=mean(aseries(i-nl:i));
sta=mean(aseries(i:i+ns));
sra(i)=sta/lta;
else
sra(i)=0;
end
end
[k]=find(sra>thresh);
if ~isempty(k)
pstime=k*dt;
else
pstime=0;
end
return;
如果您有 MATLAB 2016a 或更高版本,则可以使用 movmean
代替循环(这意味着您也不需要预分配任何内容):
lta = movmean(aseries(1:nt-ns),nl+1,'Endpoints','discard');
sta = movmean(aseries(nl+1:end),ns+1,'Endpoints','discard');
sra = sta./lta;
这里唯一的区别是您将获得没有前导和尾随零的sra
。这很可能是最快的方法。例如,如果aseries
"只有"8 MB,则此方法需要不到 0.02 秒,而原始方法需要近 6 秒!
但是,即使您没有 Matlab 2016a,考虑到您的循环,您仍然可以执行以下操作:
- 删除
else
语句 -sta(i)
已从预分配中为零。 - 从
nl+1
开始循环,而不是检查i
何时大于nl
。
因此,您的新循环将是:
for i=nl+1:nt-ns
lta = mean(aseries(i-nl:i));
sta = mean(aseries(i:i+ns));
sra(i)=sta/lta;
end
但它不会那么快。