How can I sum over specific dimensions in a n-dimensional array?

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?

 采纳的回答

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)

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Elementary Math 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by