Add some elements of one matrix with another
Show older comments
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 (5x5),
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 (8x8),
[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.
4 Comments
There is an infinite number of possible patterns to get the output from the posted inputs. I guess, you want to create a square matrix of size n + (w-1), where n is the number of matrices and w the number of columns (or rows). Then you want to add teh first matrix in the upper left corner and tep one element to the right and down for all following matrices. Correct?
Jan
on 10 Apr 2019
@vanrapa: Do you see that it would have saved time, if you mention the exact needs in the original question already? The less the readers have to guess, the more efficient is posting an answer.
Now you mention, that "n + (w-1)" is not correct, but you still let us guess, why 3 matrices of size 4x4 will produce a 8x8 output. Explaining the pattern would be much better than posting the example, which is really hard to read:#
[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]
In matrix notation this looks at least a little bit better:
[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]
Do you see it? So now you go forward by 2 elements between the matrics. But what is the step for n matrics of size m*m?
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing 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!