也许不像单线那么优雅cellfun
,但运行速度快了一个数量级以上:
sums = cumsum(M([index{:}]));
sums = diff([0, sums(cumsum(cellfun('length', index)))]);
对于大型输入,它的运行速度甚至比 JIT 加速循环快大约 4 或 5 倍。请注意,当其中的每个单元格index
包含一个包含超过 ~2000 个元素的向量时,与循环 (and cellfun
) 相比,这种方法的性能开始下降。
基准
M = rand(2103, 2030);
I = ceil(numel(M) * rand(2032, 10));
index = mat2cell(I, ones(size(I, 1), 1), size(I, 2));
N = 100;
tic
for k = 1:N
sums = zeros(1, numel(index));
for n = 1:numel(sums)
sums(n) = sum(M(index{n}));
end
end
toc
tic
for k = 1:N
sums = cellfun(@(idx) sum(M(idx)), index);
end
toc
tic
for k = 1:N
sums = cumsum(M([index{:}]));
sums2 = diff([0, sums(cumsum(cellfun('length', index)))]);
end
toc
在 MATLAB 2012a(在 2.27GHz 16 核 Intel Xeon 处理器上运行的 Windows Server 2008 R2)中执行此操作时,我得到:
Elapsed time is 0.579783 seconds.
Elapsed time is 1.789809 seconds.
Elapsed time is 0.111455 seconds.