I have two matrices A and D with sizes mxm. I want to create with these two a block matrix B size mn x mn . For example if n=5 then the output will be
B= D A A A A
A D 0 0 0
A 0 D 0 0
A 0 0 D 0
A 0 0 0 D
I have managed to create this form with many for loops but I would like a quicker solution with functions provided by matlab.
Block matrices can be created using ArrayFlatten. When two block matrices have the same shape and their diagonal blocks are square matrices, then they multiply similarly to matrix multiplication.
A block matrix is a matrix whose elements are themselves matrices, which are called submatrices. By allowing a matrix to be viewed at different levels of abstraction, the block matrix viewpoint enables elegant proofs of results and facilitates the development and understanding of numerical algorithms.
To build a block of matrix, use the numpy. block() method in Python Numpy. Blocks in the innermost lists are concatenated along the last dimension (-1), then these are concatenated along the secondlast dimension (-2), and so on until the outermost list is reached.
This should do the trick:
m = 3;
n = 5;
mn = m*n;
A_val = 4;
D_val = 2;
% Just an example, you could use rand(m) instead...
A = repmat(A_val,m);
D = repmat(D_val,m);
D_cell = repmat({D},1,n);
B = blkdiag(D_cell{:});
idx_1 = 1:m;
idx_2 = (m+1):mn;
B(idx_2,idx_1) = repmat(A,n-1,1);
B(idx_1,idx_2) = repmat(A,1,n-1);
Output:
B =
2 2 2 4 4 4 4 4 4 4 4 4 4 4 4
2 2 2 4 4 4 4 4 4 4 4 4 4 4 4
2 2 2 4 4 4 4 4 4 4 4 4 4 4 4
4 4 4 2 2 2 0 0 0 0 0 0 0 0 0
4 4 4 2 2 2 0 0 0 0 0 0 0 0 0
4 4 4 2 2 2 0 0 0 0 0 0 0 0 0
4 4 4 0 0 0 2 2 2 0 0 0 0 0 0
4 4 4 0 0 0 2 2 2 0 0 0 0 0 0
4 4 4 0 0 0 2 2 2 0 0 0 0 0 0
4 4 4 0 0 0 0 0 0 2 2 2 0 0 0
4 4 4 0 0 0 0 0 0 2 2 2 0 0 0
4 4 4 0 0 0 0 0 0 2 2 2 0 0 0
4 4 4 0 0 0 0 0 0 0 0 0 2 2 2
4 4 4 0 0 0 0 0 0 0 0 0 2 2 2
4 4 4 0 0 0 0 0 0 0 0 0 2 2 2
Average tic-toc
performance over 1000
iterations 0.00018 seconds
.
For more details about the employed functions, refer to the following links:
It is easy to do with kronecker product kron
:
m = 3; % size of the blocks
n = 5; % number of blocks
A = rand(m); % insert you matrices here
D = rand(m);
maskA = zeros(n); % maskA is the block structure of A
maskA(1,:) = 1;
maskA(:,1) = 1;
maskA(1,1) = 0;
maskD = eye(n); %maskD is the block structure of D
B = kron(maskA,A) + kron(maskD,D);
Here is a way using cell2mat
:
C = {zeros(size(A)), D , A};
mat = ones(n);
mat(1:n+1:end)=2;
mat(1,2:end)= 3;
mat(2:end,1)= 3;
out = cell2mat(C(mat));
Here's a way:
A = [10 20; 30 40]; % square matrix
D = [50 60; 70 80]; % square matrix
n = 5; % positive integer
tmp_A = repmat({A}, 1, n-1);
tmp_D = repmat({D}, 1, n-1);
result = [D, horzcat(tmp_A{:}); vertcat(tmp_A{:}), blkdiag(tmp_D{:})]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With