块矩阵创建

时间:2018-02-04 18:32:01

标签: matlab block

我有两个大小为mxm的矩阵A和D.我想用这两个创建块矩阵B size mn x mn。例如,如果n = 5,那么输出将是

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

我已经设法用许多for循环创建这个表单但是我想要一个更快的解决方案,其功能由matlab提供。

4 个答案:

答案 0 :(得分:3)

这应该可以解决问题:

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);

输出:

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

tic-toc次迭代1000的平均0.00018 seconds次见效。

有关所用功能的更多详细信息,请参阅以下链接:

答案 1 :(得分:3)

使用kronecker产品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);

答案 2 :(得分:2)

这是一种方式:

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{:})]

答案 3 :(得分:2)

以下是使用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));