通过作为单元阵列中的向量存储的索引对向量的子集求和

时间:2015-12-19 15:05:03

标签: arrays matlab vectorization

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'.

2 个答案:

答案 0 :(得分:4)

您只想根据每个单元格数组元素总结r的元素?那你确实需要cellfun

%// given
L = { ...
 [2,4,6]   % j=1
 [1,6,8]   % j=2
 [4,6] }

r = [23 1 24 5 4 3 7 8]

%// output
out = cellfun(@(x) sum(r(x)),L)
%// or in case r is not a vector, but a matrix
out = cellfun(@(x) sum(r(x(:))),L)

与:

相同
out = arrayfun(@(x) sum(r(x{:})),L)
out =

     9
    34
     8

答案 1 :(得分:4)

在这篇文章中列出了基于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{:}]))