I have an n×m×l tensor in MATLAB which I want to turn into an n×m matrix by folding the last dimension (specifically adding each scalar). How can I perform a fold / reduce of the last dimension of each entry in this tensor efficiently? More broadly, is there a nice way to apply an arbitrary function to an entire dimension of a tensor?
If it helps for understanding, the concrete tensor I have is called pixels
and the last dimension is l=3
and represents the R, G, and B values of each pixel, which I want to add to obtain brightness. The following solution I have come up with is painfully slow:
cellfun( @(x) sum(x), num2cell( pixels, 3 ) )
sum(pixels,3)
sum
allows summation over any dimension given to it, so just give it the third dimension. Trailing dimensions are cut off automatically, so your matrix will end up as size n-by-m.
Otherwise, with general functions: use a loop. Loops are no longer very slow, whilst cells definitely are:
out = zeros(size(pixels,1),size(pixels,2));
for ii = 1:size(pixels,3)
out(:,:) = YourFunc(pixels(:,:,ii));
end