L
是一个单元格。
L=
2,4,6 % j=1
1,6,8 % j=2
4,6 % j=3
r
是一个 1x8 向量:
23 1 24 5 4 3 7 8
我想向量化这段代码:
UC=zeros(1,J);
for j=1:J
if ~isempty(L{j})
UC(j)=sum(r(L{j}));
end
end
我试过这个:
UC = arrayfun(@(x)r(x), L, 1, 'UniformOutput', false);
但看起来细胞不适合这个功能。
Error using subsindex
Function 'subsindex' is not defined for values of class 'cell'.
最佳答案
这篇文章中列出的是一种几乎基于accumarray
的矢量化方法。 .我将其称为几乎矢量化,因为它使用 cellfun
这并不是真正的矢量化方式,但由于它仅使用它来查找每个单元格的长度,因此其影响很小。这是实现-
lens = cellfun('length',L)
id = zeros(1,sum(lens))
id([1 cumsum(lens(1:end-1))+1]) = 1;
out = accumarray(cumsum(id(:)),r([L{:}]))
关于arrays - 通过在元胞数组中存储为向量的索引对向量的子集求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34372137/