Matlab - 基于给定索引的向量元素组

时间:2013-10-26 11:12:31

标签: matlab vector sum indices accumarray

我重新提出了一个我本周问过的问题,由于缺少标签,这个问题被忽视了(基本上只有我才看到)。

我有两个大的向量,值和索引。我需要使用索引来对值的元素求和,就像在这个强力示例中一样:

% The two vectors, which are given, look like this:
N = 3e7;
values = (rand(N, 1) > 0.3);
indices = cumsum(ceil(4*rand(N, 1)));
indices = [0; indices(find(indices > 1, 1, 'first'):find(indices < N, 1, 'last')); N];
HH = numel(indices) - 1;

% This is the brute force solution
tic
out1 = zeros(HH, 1);
for hh = 1:HH
  out1(hh) = sum(values((indices(hh)+1):indices(hh+1)));
end
toc

更有效的方法如下:

tic
indices2 = diff(indices);
new_inds = (1:HH+1)';
tmp = zeros(N, 1);
tmp(cumsum(indices2)-indices2+1)=1;
new_inds_long = new_inds(cumsum(tmp));
out2 = accumarray(new_inds_long, values);
toc

更好的解决方案是:

tic
out3 = cumsum(values);
out3 = out3(indices(2:end));
out3 = [out3(1); diff(out3)];
toc

三种解决方案是等效的

all(out1 == out2)
all(out1 == out3)

问题是:因为这实际上是一个基本功能,是否有更快,已知的方法/功能做同样的事情,我可能会忽略或我只是不知道?

1 个答案:

答案 0 :(得分:0)

如果生成索引不仅仅是其他人的假人,那么可以改进。目前,您正在浪费3/4生成的数字。 1)确定所需的索引数(二项分布)2)仅生成使用的索引。

相关问题