Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum subsets of vector by indices stored as vectors in cell array

L is a cell.

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

r is a vector 1x8:

23 1 24 5 4 3 7 8

I want to vectorize this code:

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 looks like cells are not suitable for this function.

Error using subsindex
Function 'subsindex' is not defined for values of class 'cell'.
like image 426
Klausos Klausos Avatar asked Feb 08 '23 06:02

Klausos Klausos


2 Answers

Listed in this post is an almost vectorized approach based upon accumarray. I am calling it as almost vectorized because it uses cellfun which isn't really a vectorized way, but since it uses it to find the lengths of each cell only, so its effect would 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{:}]))
like image 124
Divakar Avatar answered Feb 11 '23 22:02

Divakar


You just want to sum up elements of r according to every of your cell array elements? Then you need indeed 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)

which is the same as:

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

out =

     9
    34
     8
like image 40
Robert Seifert Avatar answered Feb 11 '23 22:02

Robert Seifert