Matrix Sum

15 views (last 30 days)
SB
SB on 10 Dec 2011
Hi!
I have a question I think it's pretty basic, but I can´t seem to find the answer!
I have 'n' 3x3 matrices (B), and I want to construct another 3x3 matrix (A) in which each entry is the sum of the similar entries of the initial 3x3 B matrices:
A(ij) = Bij (1) + Bij (2) + ... + Bij (n)
The in brackets numbers are the corresponding B matrices.
The way i tried to solve this was by making two 'for' loops - one for i and another for j. The problem I'm having is with the summation itself. I can work pass that if I code the summation 'by hand', that is, explicitating each member of the sum - the way I wrote it above. This could be a sollution if I had only 2 or 3 matrices. But I have 20 or 30 B matrices, which makes it very boring (and very very bad programming) to write all explicitly.
I know this is a very basic situation, but I'm reletively new at MatLab, so any help is really appreciated!
SB

Answers (4)

Jan
Jan on 10 Dec 2011
Store the B matrices in a CELL instead of using different names:
n = 30;
B = call(1, n);
for i = 1:n
B{i} = rand(3, 3);
end
Now the sum:
B2 = cat(3, B{:});
A = sum(B2, 3);

bym
bym on 10 Dec 2011
just add the B matricies. For example:
A = ones(3) + eye(3) + magic(3);

Sven
Sven on 10 Dec 2011
You can (and possibly should, depending on what you want to do next) turn your N 3-by-3 matrices into a single 3-by-3-by-N matrix.
Then you could just write:
A = sum(B,3);
The above will make A as the sum of B along the 3rd dimension. There are lots of neat things you can do in MATLAB once you work with matrices like this.
To get B as a 3-by-3-by-N matrix you can do many things... one of them is to concatenate in the 3rd dimension as follows:
B = cat(3, rand(3,3), ones(3,3), zeros(3,3), rand(3,3))
Another way to get B would be in a loop over each of the N layers:
B = zeros(3,3,N); % This is called "preallocation". A good idea for big matrices.
for i = 1:N
B(:,:,i) = your3by3(N); % Put in this slice of B
end

Walter Roberson
Walter Roberson on 10 Dec 2011

Tags

Community Treasure Hunt

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

Start Hunting!