向量化此循环 [英] Vectorize this loop
问题描述
我在MATLAB中有以下循环:
I have the following loop in MATLAB:
n = 20000
rho=0.9;
sigma=[0.1 0.2 0.3];
epsilon = normrnd(0,1, 3, n);
z = NaN(1,n);
z(1,1) = 0;
for i=2:n
z(1,i) = rho * z(1,i-1) + sigma* epsilon(:,i);
end
我尝试通过以下方式向量化它:
I tried vectorizing it by doing:
z(1,2:end) = rho * z(1,1:end-1) + sigma * epsilon
它没有用.我知道问题是该位:z(1,2:end) = rho * z(1,1:end-1)
不是递归的.
It didn't work. I understand that the problem is that this bit: z(1,2:end) = rho * z(1,1:end-1)
is not recursive.
我该如何解决?
推荐答案
在一个充满 crazy fast parallel processors and almost-free memory latency machines
的世界末日世界中,像bsxfun
和matrix multiplication
这样的矢量化工具可以轻松生成20,000个内核,一个迷失的灵魂,拼命试图将这样的问题向量化,可能会冒险进入这样的情况-
In a post apocalyptic world filled with crazy fast parallel processors and almost-free memory latency machines
, where vectorizing tools like bsxfun
and matrix multiplication
could easily spawn across 20,000 cores, one lost soul desperately trying to vectorize such a problem could venture into something like this -
parte1 = tril(rho.^(bsxfun(@minus,(0:n-2)',0:n-2)));
parte2 = sigma*epsilon(:,2:end);
z = [0 parte2*parte1.']
总的来说,它不应该提高内存效率,因此不太可能很快..现在,但是它旨在演示一种跟踪并应用递归的方法一个向量化的解决方案.
In all seriousness, it's not supposed to be memory-efficient and thus, isn't likely to be fast .. now, but is meant to demonstrate a way to trace the recursion and apply it for a vectorized solution.
这篇关于向量化此循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!