MATLAB: How to properly sum 3D matrixes

3d matrix sum

Ok, I need to sum a 3D matrix, say:
X=sym('x',[1 3])
Y=sym('y',[1 3])
Z=sym('z',[1 3])
for n=1:3
for m=1:3
for k=1:3
M(n,m,k)=X(n)*Y(m)*Z(k)
end
end
end
My objective is to sum the 3D matrixes so all the elements that are in the third direction appear as a sum on a 2D matrix. I tried using sum(M,3) but it says "Input arguments must be two-dimensional"
Basically I want the 3D matrix M to look like this:
M=[(x1*y1*(z1+z2+z3)) (x1*y2*(z1+z2+z3)) (x1*y3*(z1+z2+z3))
(x2*y1*(z1+z2+z3)) (x2*y2*(z1+z2+z3)) (x2*y3*(z1+z2+z3))
(x3*y1*(z1+z2+z3)) (x3*y2*(z1+z2+z3)) (x3*y3*(z1+z2+z3))]
Thanks in advance

Best Answer

Use this function:
function M=sumnd(M,dim)
s=size(M);
M=permute(M,[setdiff(1:ndims(M),dim),dim]);
M=reshape(M,[],s(dim));
M=sum(M,2);
s(dim)=1;
M=reshape(M,s);
end
Code:
A=sumnd(M,3) ;
A = simplify(A) ;
Result:
[ x1*y1*(z1 + z2 + z3), x1*y2*(z1 + z2 + z3), x1*y3*(z1 + z2 + z3)]
[ x2*y1*(z1 + z2 + z3), x2*y2*(z1 + z2 + z3), x2*y3*(z1 + z2 + z3)]
[ x3*y1*(z1 + z2 + z3), x3*y2*(z1 + z2 + z3), x3*y3*(z1 + z2 + z3)]