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..
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.
out = blkdiag(m1,m2,m3,m4,...),
and go from there reading the documentation forblkdiag
mathworks.com/help/matlab/ref/blkdiag.html – blak
varies so how can you use the lineblkdiag(m1, m2, m3, ...)
when you don't knowk
? – user3701257A = zeros(k*n, k*n)
and then copy stuff in at the appropriate places. If you're doing stuff likeA = [A, blah];
, that will be inefficient – Matthew Gunn