【发布时间】:2015-04-02 19:12:37
【问题描述】:
我在 MATLAB 中有一个 for 循环,它按如下方式计算正弦函数的总和:
% preliminary constants, etc.
tTot = 2;
fS = 10000;dt = 1/fS; % total time, sampling rate
Npts = tTot * fS; %number of points
t = dt:dt:tTot;
c1 = 2*pi/tTot;
c2 = pi/fS;
s = zeros(1,Npts)
% loop to optimize:
for(k=1:Npts/2)
s = s + sin(c1*k*t - c2*k*(k-1))
end
基本上,随着Npts 变大,单行 for 循环变得非常慢。困难在于我将由参数k 定义的向量求和,而不是k。
有没有办法通过矢量化来提高效率?到目前为止,我采用的一种方法是定义一个矩阵并对结果求和,但这会给我一个较大向量的内存不足错误:
[K,T] = meshgrid(1:1:Npts,t);
s = sum(sin(c1*K.*T - c2*K.*(K-1)),2);
【问题讨论】:
标签: matlab vectorization