在Matlab中,有没有一种快速的方法用A和B块填充(稀疏)矩阵:
A, B, 0, 0, 0
B, A, B, 0, 0
0, B, A, B, 0
0, 0, B, A, B
0, 0, 0, B, A
我尝试了此代码
e=full([A B; B A]);
e1=e;
for i=1:n
e=blkdiag(e,e1);
end
答案 0 :(得分:3)
您可以执行以下操作(将功能保存到文件blktritoep.m
中):
function C = blktritoep(A, B, nb)
% A, B must be square of and same size for this to work
% nb = number of times A gets repeated on the diagonal of C
A = sparse(A); % Does nothing if A is already sparse
B = sparse(B); % Idem
C = kron(diag(ones(nb,1)), A) + kron(diag(ones(nb-1,1), 1), B) + ...
kron(diag(ones(nb-1,1), -1), B);
end
例如,我得到的输出
A = ones(2,2);
B = -2 * ones(2,2);
C = blktritoep(A, B, 3);
full(C) % Result is sparse, just for pretty printing!
是
ans =
1 1 -2 -2 0 0
1 1 -2 -2 0 0
-2 -2 1 1 -2 -2
-2 -2 1 1 -2 -2
0 0 -2 -2 1 1
0 0 -2 -2 1 1