[英]How to speed up this matlab code which is already vectorized
我正在尝试加快以下代码中的步骤 1-4(其余的设置将针对我的实际问题预先确定。)
% Given sizes:
m = 200;
n = 1e8;
% Given vectors:
value_vector = rand(m, 1);
index_vector = randi([0 200], n, 1);
% Objective: Determine the values for the values_grid based on indices provided by index_grid, which
% correspond to the indices of the value in value_vector
% 0. Preallocate
values = zeros(n, 1);
% 1. Remove "0" indices since these won't have values assigned
nonzero_inds = (index_vector ~= 0);
% 2. Examine only nonzero indices
value_inds = index_vector(nonzero_inds);
% 3. Get the values for these indices
nonzero_values = value_vector(value_inds);
% 4. Assign values to output (0 for those with 0 index)
values(nonzero_inds) = nonzero_values;
这是我对代码的这些部分的分析:
index_vector
将包含需要index_vector
零。 O(n) 因为它只是一次遍历向量一个元素并检查(值∨ 0)的问题index_vector
并保留上一步中非零的那些index_vector
元素,并且对于每个元素,我们访问value_vector
是 O(1)。nonzero_inds
每个元素,访问相应的values
索引,访问相应的nonzero_values
元素,并将其分配给values
向量。上面的代码在 3.8GHz 的 4 核上运行第 1-4 步大约需要 5 秒。 大家对如何加快速度有任何想法吗? 谢谢。
哇,我发现了一件非常有趣的事情。 我在“相关”部分看到了这个链接,关于索引向量有时在 Matlab 中效率低下,所以我决定尝试一个 for 循环。 这段代码最终快了一个数量级!
for i = 1:n
if index_vector(i) > 0
values(i) = value_vector(index_vector(i));
end
end
编辑:另一件有趣的事情,不幸的是对我的问题不利。 此解决方案的速度取决于 index_vector 中零的数量。 使用index_vector = randi([0 200]);
,一小部分值为零,但如果我尝试index_vector = randi([0 1])
,大约一半的值将为零,然后上述 for 循环实际上慢了一个数量级。 但是,使用~=
而不是>
加快循环速度,使其处于类似的数量级。 非常有趣和奇怪的行为。
如果你坚持使用 matlab 和你想要的算法流程,而不是在 fortran 或 c 中这样做,这里有一个小小的开始:
将randi
更改为 rand,并通过强制转换为uint8
舍入,并使用>
逻辑运算,该运算由于某种原因在我结束时速度更快
总结:
value_vector = rand(m, 1 );
index_vector = uint8(-0.5+201*rand(n,1) );
values = zeros(n, 1);
values=value_vector(index_vector(index_vector>0));
这在我结束时提高了 1.6 倍
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.