summing over a multi-dimensional cartesian product using nested arrayfun commands
Show older comments
I have an anonymous function with multiple arguments and I want to sum over all of them. For example, consider the simple function
U = @(i,j) i+j;
I = 1:3; J = 1:3;
The command
sumJ = @(I,J) sum(arrayfun(@(j)sum(U(I,j)),J)
will sum over all pairs in the cartesian product IxJ
I'd like to do the analogous thing for
V = @(i,j,k) i + j + k
I realize that there are many other ways of doing this simple summation, it's just an easy example. For my more complex problem, I believe I would need to use nested arrayfun commands, but can't figure out how to do this. Thanks very much for any help.
Accepted Answer
More Answers (1)
Maybe this can help:
U = @(m,n)m+n;
V = @(M,n)sum(arrayfun(@(m)U(m,n),M));
W = @(M,N)sum(arrayfun(@(n)V(M,n),N));
A = 1:3;
B = 1:3;
W(A,B)
But note that loops are often faster than arrayfun or cellfun. And even faster would be to consider using bsxfun instead of arrayfun or a loop:
X = bsxfun(@plus,A,B(:));
sum(X(:))
4 Comments
Leo Simon
on 23 Nov 2015
You could combine bsxfun and cellfun:
>> U = @(m,n,o)m+n+o;
>> V = @(M,N,o)sum(sum(bsxfun(@(m,n)U(m,n,o),M,N(:))));
>> W = @(M,N,O)sum(cellfun(@(o)V(M,N,o),num2cell(O)));
>> W(1:3,1:3,1:4)
ans = 234
Leo Simon
on 24 Nov 2015
Guillaume
on 24 Nov 2015
The purpose of N(:) is simply to transpose N. It is the same as N.'.
In Stephen's answer bsxfun is used to apply your function to the cartesian product of the vectors. Hence one vector needs to be along one dimension, the other vector along another. bsxfun is equivalent to repmat'ing each vector along the dimension of the other (without needing the memory for the repmat'ed matrix). My answer's basically does this repmat'ing explicitly, using ndgrid.
That's why I said it was a shame that bsxfun is limited to two inputs. An hypothetical bsxfun that allowed a arbitrary number of inputs would have allowed you to write:
W = bsxfun(V, I, J', permute(K, [3 2 1]), permute(L, [4 3 2 1]);
sumall = sum(W:));
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!