How I compute multiple sum in matlab for 4D matrix?
Show older comments
How I compute multiple sum in matlab for 4D matrices as below? U and V are 4D matrices.

12 Comments
Mehdi
on 11 Sep 2018
Mehdi
on 11 Sep 2018
Amir Xz
on 11 Sep 2018
Why you don't use "for" loops?
U = rand(5,4,3,2);
V = rand(5,4,3,2);
I=5;J=4;M=2;N=3;
sumUV=0;
for i=1:I
for j=1:J
for k=1:I
for r=2:M
for s=2:M
for q=2:N
sumUV = sumUV + U(i,j,q,r)*V(k,j,q,s);
end
end
end
end
end
end
Mehdi's comment relocated here:
in Maple you can simply do it by add command like below:
A=add(add(add(add(add(add(U[i,j,q,r]*V[k,j,q,s],i=0..I),j=0..J),k=0..I),r=1..M))s=1..M),q=1..N)
is there any similar way to do it in Matlab?
No, I mean you should do as I posted in my answer below. Reading the sum() commmand documentation would also probably be beneficial.
Answers (1)
Notice that the only indices shared between U and V are j and q. Therefore, you can minimize multiplication operations as follows,
partialU=sum(sum(U,4),1); %sum over i and r
partialV=sum(sum(V,4),1); %sum over k and s
A=sum(partialU(:).*partialV(:)); %sum over j and q
6 Comments
Matt J
on 11 Sep 2018
In fact, it would probably be faster to do this as a vector-vector inner product,
A= partialU(:).'*partialV(:);
Mehdi
on 11 Sep 2018
What about if U and V be symbolic parameters?
But they are not. You said that they are numeric arrays, which is a smart choice, since you said that speed is important here. However, sum() should still work with symbolic variables. There is also symsum().
I don't see how add is simpler. Your expressions using add are a lot longer than the ones I've presented using sum.
Mehdi
on 11 Sep 2018
Mehdi
on 11 Sep 2018
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!