Search code examples
matlabmatrixdiagonal

Algorithmically construct block matrices (matlab)


Let Matrices = [A B C D] be a set of square matrices. I want to construct

H = [A B C D;
     B A B C;
     C B A B;
     D C B A]

If all I was interested in was the 4 by 4 case, then this would be enough. However, I want to construct the analogous matrix when Matrices = [A B C D E F] etc. What code could I write to do this?


Solution

  • This can be done as follows:

    • Concatenate the matrices into a 3D array;
    • Build the basic with numbers instead of matrices using toeplitz;
    • Extend this structure so that using linear indexing into the 3D array produces the desired result.

    N = 2; % matrix size
    M = 3; % number of matrices
    matrices = arrayfun(@(x) {randi(9,N)}, 1:M); % input matrices
    matrices_3D = cat(3, matrices{:}); % concatenate the matrices along the third dim
    ind1 = repmat(reshape(1:N^2, N, N), M, M); % linear indices within each matrix
    ind2 = (repelem(toeplitz(1:M), N, N)-1)*N^2; % linear indices to select the matrices
    result = matrices_3D(ind1 + ind2); % build result
    

    Example run:

    >> celldisp(matrices)
    matrices{1} =
         1     4
         2     6
    matrices{2} =
         6     4
         5     9
    matrices{3} =
         5     4
         6     5
    >> result
    result =
         1     4     6     4     5     4
         2     6     5     9     6     5
         6     4     1     4     6     4
         5     9     2     6     5     9
         5     4     6     4     1     4
         6     5     5     9     2     6