I have overcomplicated a relatively simple problem, which essentially boils down to summing over all dimensions of the array with the exception of one element from the same list
What release of MATLAB are you using? If you're using release R2018b or later, use the vector dimension argument functionality introduced in that release. Let's define a sample 4-dimensional array to start. sz = [2 3 4 5];
n = numel(sz);
A = reshape(1:prod(sz), sz);
Define a vector containing all the dimensions, and preallocate a cell array to hold the results of summing in all dimensions but one for each of the dimensions of A.
dims = 1:n;
results = cell(1, n);
Now let's do the summation.
for excludedDim = 1:n
D = dims;
D(excludedDim) = [];
results{excludedDim} = sum(A, D);
end
If you look at each element of results, it has the same size as A in the dimension that was excluded from summation and size 1 in all the others. This does mean that some of the elements in results have fewer dimensions than A does due to trailing singleton dimensions being dropped.
Best Answer