How to sum multiple matrices?

4 views (last 30 days)
Hello, I'm new in matlab and I need some help please. I have 12 matrix s1...s12 which I want to 2 by 2 make a Kronecker tensor product of them and then sum the results. for example, I want the product of s1 and s2, s1 and s3,s1 and s4,... and then sum them all.
Thanks in advance.

Accepted Answer

Stephen23
Stephen23 on 16 Aug 2018
Edited: Stephen23 on 16 Aug 2018
"I'm new in matlab and I need some help please. I have 12 matrix s1...s12..."
That is the problem right there. Numbered variables are a sign that you are doing something wrong. Instead of using numbered variables you should be using simple and efficient indexing with an ND array or a cell array. Read this to know why:
"...which I want to 2 by 2 make a Kronecker tensor product of them and then sum the results. for example, I want the product of s1 and s2, s1 and s3,s1 and s4,... and then sum them all."
So put them into one array and use loop/s. Something like this:
A = rand(2,2,12); % 12 matrices
V = 2:size(A,3);
N = numel(V);
C = cell(1,N);
for k = 1:N
C{k} = kron(A(:,:,1),A(:,:,V(k)));
end
The kron outputs are in the cell array C. To sum them you might want something like this:
>> sum(cat(3,C{:}),3)
ans =
1.7813 1.1161 3.8904 2.4375
1.6809 1.2158 3.6710 2.6554
6.0980 3.8206 5.6882 3.5638
5.7542 4.1622 5.3674 3.8824
But this depends on your definition of "sum" for multiple matrices, which you have not explained to us. See also:

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!