MATLAB: Create a block diagonal matrix with same repeating block

17,314

Solution 1

you can use kron for that.

M = kron(X,Y)

returns the Kronecker tensor product of X and Y. The result is a large array formed by taking all possible products between the elements of X and those of Y. If X is m-by-n and Y is p-by-q, then kron(X,Y) is m*p-by-n*q. So in your case something like this will do:

M = kron(eye(L),K)

with L the # of blocks.

Solution 2

tmp = repmat({K},d,1);
M = blkdiag(tmp{:});

You should never use eval, or go into for loops unnecessarily. Kron is a very elegant way. Just wanted to share this as it also works.

Solution 3

The following should work:

d=5; K=eye(3); T = cell(1,d);

for j=1:d T{j} =K; end

M = blkdiag(T{:})

Share:
17,314
steadyfish
Author by

steadyfish

Nothing deterministic about me..

Updated on June 23, 2022

Comments

  • steadyfish
    steadyfish almost 2 years

    I have a matrix K of dimensions n x n. I want to create a new block diagonal matrix M of dimensions N x N, such that it contains d blocks of matrix K as its diagonal.

    I would have directly used M = blkdiag(K,K,K) etc. had d been smaller. Unfortunately, d is very large and I don't want to manually write the formula with d exactly same arguments for the blkdiag() function.

    Is there any shorter, smarter way to do this?

  • steadyfish
    steadyfish almost 11 years
    Thanks for the hint @natan. I tried a couple of combinations and figured that following gives me what I'm looking for - M = kron(eye(d),K)
  • Youwei Liang
    Youwei Liang almost 5 years
    Actually, this is faster than using Kron: K=rand(3); tic;G = kron(eye(2000),K);toc Elapsed time is 0.122015 seconds. ` tic;tmp = repmat({K},2000,1);M = blkdiag(tmp{:});toc` Elapsed time is 0.036623 seconds.