I am trying to do an elementwise insertion of a small matrix (2x2) along the diagonal of a large matrix (10x10 say). Overlapping values are added, and the small matrix is only inserted where it can fit fully inside the large matrix.
I have achieved this using a for loop, but am curious whether the process can be vectorised.
function M = TestDiagonal()
N = 10;
miniM = [1, -1; -1, 1];
M = zeros(N);
for i = 1:N-1
M(i:i+1,i:i+1) = M(i:i+1,i:i+1) + miniM;
end
end
Giving the desired matrix
1 -1 0 0 0 0 0 0 0 0
-1 2 -1 0 0 0 0 0 0 0
0 -1 2 -1 0 0 0 0 0 0
0 0 -1 2 -1 0 0 0 0 0
0 0 0 -1 2 -1 0 0 0 0
0 0 0 0 -1 2 -1 0 0 0
0 0 0 0 0 -1 2 -1 0 0
0 0 0 0 0 0 -1 2 -1 0
0 0 0 0 0 0 0 -1 2 -1
0 0 0 0 0 0 0 0 -1 1
In the general case, the input will always be square, but can take any size. The step dimension will always be equal to 1.