MATLAB: How to sum over specific dimensions in a n-dimensional array

n dimensional arraysum

I have an array of unknown dimension n. I want to sum the values of the array over the last d dimensions in order to get a new array of dimension n-d. My current code is:
% Determine the number of dimensions n in the array and d
n = ndims(x);
d = n/2;
% sum over the last d dimensions
for i = 1:d
x = sum(x, n+1-d);
end
Is there a way to avoid the for loop and do this in a more efficient way?

Best Answer

Join the trailing dimensions at first:
x = rand(2,3,4,5,6);
d = 3;
n = ndims(x);
s = num2cell(size(x));
y = reshape(x, s{1:n-d}, []);
result = sum(y, n-d+1)