2
votes

What would be the most efficient way to build this matrix given that I have each of the nxn matrices.

I was thinking of creating a cell array and iterating through that using a nested for loop but for large k this would be very inefficient..

enter image description here

1
out = blkdiag(m1,m2,m3,m4,...), and go from there reading the documentation for blkdiag mathworks.com/help/matlab/ref/blkdiag.htmlbla
@bla But k varies so how can you use the line blkdiag(m1, m2, m3, ...) when you don't know k?user3701257
creating a cell array and iterating through it with k would be fine too. The key is you do A = zeros(k*n, k*n) and then copy stuff in at the appropriate places. If you're doing stuff like A = [A, blah];, that will be inefficientMatthew Gunn
@user3701257 you should upvote and accept answers that work for youMatthew Gunn

1 Answers

1
votes

Example how to use blkdiag with arbitrary number of input matrices:

m = {[1,2; 3, 4]; [10, 11, 12; 13, 14, 15; 16, 17, 18]};  %cell array of matrices
A = blkdiag(m{:})

You can then touch it up by copying matrices into the big matrix A

for(i=1:k-1)
    row_begin = 1 + (i-1)*n;
    row_end   = row_begin + n - 1;
    col_begin = 1 + i*n;
    col_end   = col_begin + n - 1;
    A(row_begin:row_end, col_begin:col_end) = B
end

etc...

If your matrix is extremely large but extremely sparse and your algorithm preserves sparsity, you may consider constructing a sparse matrix.