I am trying to insert small square matrices along the diagonal of a large matrix. These matrices are contained in a 3D array, and have different values. Overlapping values are to be added, and the small matrices are only inserted where they can fit fully inside the large matrix. The step dimension will always be equal to 1.
I have achieved an answer through the use of for-loops, but am attempting to vectorise this code for efficiency. How would I do this? The current, unvectorised code is shown below.
function M = TestDiagonal2()
N = 10;
n = 2;
maxRand = 3;
deepMiniM = randi(maxRand,n,n,N+1-n);
M = zeros(N);
for i = 1:N+1-n
M(i:i+1,i:i+1) = M(i:i+1,i:i+1) + deepMiniM(:,:,i);
end
end
The desired result is an `N`x`N` matrix with `n+1` diagonals populated:
3 1 0 0 0 0 0 0 0 0
4 5 3 0 0 0 0 0 0 0
0 3 3 3 0 0 0 0 0 0
0 0 1 6 3 0 0 0 0 0
0 0 0 4 4 4 0 0 0 0
0 0 0 0 2 3 2 0 0 0
0 0 0 0 0 2 6 2 0 0
0 0 0 0 0 0 4 2 2 0
0 0 0 0 0 0 0 3 3 1
0 0 0 0 0 0 0 0 3 3
1 Comment
Stephen Cobeldick (view profile)
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/486571-vectorisation-of-code-for-insertion-of-n-x-n-matrices-in-a-3d-array-along-the-diagonal-of-a-large-ma#comment_758609
Sign in to comment.