MATLAB: How can i simplify this expression

expressionnested forsimplify

u is 37x37x37x37 complex matrix
h is 37*37 complex matrix
i want to simplify this expression:
N=37;
res=zeros(N,N,N,N);
for i=1:N
for j=1:N
res(:,:,i,j)=h(i,j)*u(:,:,i,j);
end
end
res=sum(res,[3 4]);

Best Answer

Hi Dror,
n1 = 10; % in case the dimensions are not all the same
n2 = 6;
n3 = 33;
n4 = 28;
u = rand(n1,n2,n3,n4) + i*rand(n1,n2,n3,n4);
h = rand(n3,n4) + i*rand(n3,n4);
res = zeros(n1,n2,n3,n4);
for ii = 1:n3 % I don't use i as a sum variable so i can stay as sqrt(-1)
for j = 1:n4
res(:,:,ii,j)=h(ii,j)*u(:,:,ii,j);
end
end
res = sum(res,[3 4])
% different way
uu = reshape(u,n1*n2,n3*n4);
hh = reshape(h,n3*n4,1);
res1 = reshape(uu*hh,n1,n2) % same thing