算法构造块矩阵(matlab)
Algorithmically construct block matrices (matlab)
设Matrices = [A B C D]
为一组方阵。我要建设
H = [A B C D;
B A B C;
C B A B;
D C B A]
如果我只对 4 x 4 的情况感兴趣,那么这就足够了。但是,我想在 Matrices = [A B C D E F]
等时构造类似矩阵。我可以编写什么代码来做到这一点?
这可以按如下方式完成:
- 将矩阵连接成一个 3D 数组;
- 使用数字而不是矩阵构建基础
toeplitz
;
- 扩展此结构,以便在 3D 数组中使用 linear indexing 产生所需的结果。
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
示例运行:
>> 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
设Matrices = [A B C D]
为一组方阵。我要建设
H = [A B C D;
B A B C;
C B A B;
D C B A]
如果我只对 4 x 4 的情况感兴趣,那么这就足够了。但是,我想在 Matrices = [A B C D E F]
等时构造类似矩阵。我可以编写什么代码来做到这一点?
这可以按如下方式完成:
- 将矩阵连接成一个 3D 数组;
- 使用数字而不是矩阵构建基础
toeplitz
; - 扩展此结构,以便在 3D 数组中使用 linear indexing 产生所需的结果。
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
示例运行:
>> 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