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)]
Best Answer