MATLAB: Add some elements of one matrix with another

MATLABmatrix element additionsmatrix manipulation

Hello,
I need to add some elements of several ‘n’ square matrices in a particular fashion and append zeros in the rest of the elements.
Let’s say for example, there are 4 2 x 2 square matrices,
1st matrix = [1 2; 3 4]
2nd matrix = [5 6; 7 8]
3rd matrix = [9 10; 11 12]
4th matrix = [13 14; 15 16]
Then resultant matrix should be (5×5),
R = [1 2 0 0 0;
3 4+5 0+6 0 0;
0 0+7 0+8+9 0+10 0;
0 0 0+11 0+12+13 0+14;
0 0 0 0+15 0+16]
But if there are three 4 x 4 input matrices,
1st matrix = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
2nd matrix = [a b c d; e f g h; i j k l; m n o p]
3rd matrix = [A B C D; E F G H; I J K L; M N O P]
Then resultant matrix should be (8×8),
[1 2 3 4 0 0 0 0;
5 6 7 8 0 0 0 0;
9 10 11+a 12+b 0+c 0+d 0 0;
13 14 15+e 16+f 0+g 0+h 0 0;
0 0 i j k+A l+B 0+C 0+D;
0 0 m n o+E p+F 0+G 0+H;
0 0 0 0 0+I 0+J 0+K 0+L;
0 0 0 0 0+M 0+N 0+O 0+P]
So now it will go forward by 2 elements between the matrices and for 6*6 matrices, it will go forward by 3 elements between the matrices and so on.
The step for n matrices of size 2*2 is n+1 and 4*4 is 2(n+1) and 6*6 is 3(n+1) and so on.
So is there any way by which I can compute this resultant matrix for ‘n’ even square matrices?
Thanks in advance.

Best Answer

Using a straightforward loop:
C = {[1,2;3,4],[5,6;7,8],[9,10;11,12],[13,14;15,16]};
A = cat(3,C{:}); % not strictly required, but ensures same size matrices.
S = size(A);
N = S(3)+S(2)-1; % adjust to suit step, etc.
B = zeros(N,N,S(3));
for k = 1:S(3)
V = k:k+S(1)-1;
B(V,V,k) = A(:,:,k);
end
Z = sum(B,3)
Giving:
Z =
1 2 0 0 0
3 9 6 0 0
0 7 17 10 0
0 0 11 25 14
0 0 0 15 16