Sum of subsets of a vector by indices stored as vectors in an array of cells

L is a cell.

L=
 2,4,6   % j=1
 1,6,8   % j=2
 4,6     % j=3

r - 1x8 vector:

23 1 24 5 4 3 7 8

I want to highlight this code in my file:

UC=zeros(1,J);
for j=1:J
    if ~isempty(L{j})                      
        UC(j)=sum(r(L{j}));
    end
end

I tried this:

UC = arrayfun(@(x)r(x), L, 1, 'UniformOutput', false);

but it seems that the cells are not suitable for this function.

Error using subsindex
Function 'subsindex' is not defined for values of class 'cell'.
+4
source share
2 answers

This column presents an almost vectorized approach based on accumarray. I call it almost vectorized because it uses cellfunwhich is not really a vectorized way, but because it uses it to find the lengths of each cell, so its effect will be minimal. Here's the implementation -

lens = cellfun('length',L)
id = zeros(1,sum(lens))
id([1 cumsum(lens(1:end-1))+1]) = 1;
out = accumarray(cumsum(id(:)),r([L{:}]))
+4
source

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
+4

Source: https://habr.com/ru/post/1620886/


All Articles