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'.
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{:}]))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With