How I compute multiple sum in matlab for 4D matrix?
Afficher commentaires plus anciens
How I compute multiple sum in matlab for 4D matrices as below? U and V are 4D matrices.

12 commentaires
Mehdi
le 11 Sep 2018
Mehdi
le 11 Sep 2018
Amir Xz
le 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.
Réponses (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 commentaires
Matt J
le 11 Sep 2018
In fact, it would probably be faster to do this as a vector-vector inner product,
A= partialU(:).'*partialV(:);
Mehdi
le 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
le 11 Sep 2018
You should edit your original post with this new equation and information about q_r and q_s. The new expression is rather unclear. You have the symbol q being used for two different things, both as a symbolic variable and as an index of summation.
Mehdi
le 11 Sep 2018
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!