用于沿大矩阵的对角线在 3D 数组中插入 n x n 矩阵的代码向量化
Vectorisation of code for insertion of n x n matrices in a 3D array along the diagonal of a large matrix
与 一样,我正在尝试沿大矩阵的对角线插入小方阵。但是,这些矩阵现在包含在一个 3D 数组中,并且具有不同的值。和以前一样,要添加重叠值,并且只将小矩阵插入到可以完全放入大矩阵的位置。步长维度将始终等于 1。
我已经通过使用 for 循环找到了答案,但我正在尝试矢量化此代码以提高效率。我该怎么做?当前未向量化的代码如下所示。
function M = TestDiagonal2()
N = 10;
n = 2;
maxRand = 3;
deepMiniM = randi(maxRand,n,n,N+1-n);
M = zeros(N);
for i = 1:N+1-n
M(i:i+n-1,i:i+n-1) = M(i:i+n-1,i:i+n-1) + deepMiniM(:,:,i);
end
end
期望的结果是 N
xN
矩阵,其中填充了 n+1
条对角线:
3 1 0 0 0 0 0 0 0 0
4 5 3 0 0 0 0 0 0 0
0 3 3 3 0 0 0 0 0 0
0 0 1 6 3 0 0 0 0 0
0 0 0 4 4 4 0 0 0 0
0 0 0 0 2 3 2 0 0 0
0 0 0 0 0 2 6 2 0 0
0 0 0 0 0 0 4 2 2 0
0 0 0 0 0 0 0 3 3 1
0 0 0 0 0 0 0 0 3 3
这利用了implicit expansion, as well as sparse
to add values at coincident indices, and (:)
indexing to linearize a matrix in the usual column-major order。
ind1 = repmat((1:n).', n, 1) + (0:N-n); % column indices for the sum
ind2 = repelem((1:n).', n) + (0:N-n); % row indices for the sum
M = full(sparse(ind1(:), ind2(:), deepMiniM(:), N, N)); % sum over those indices
与
我已经通过使用 for 循环找到了答案,但我正在尝试矢量化此代码以提高效率。我该怎么做?当前未向量化的代码如下所示。
function M = TestDiagonal2()
N = 10;
n = 2;
maxRand = 3;
deepMiniM = randi(maxRand,n,n,N+1-n);
M = zeros(N);
for i = 1:N+1-n
M(i:i+n-1,i:i+n-1) = M(i:i+n-1,i:i+n-1) + deepMiniM(:,:,i);
end
end
期望的结果是 N
xN
矩阵,其中填充了 n+1
条对角线:
3 1 0 0 0 0 0 0 0 0
4 5 3 0 0 0 0 0 0 0
0 3 3 3 0 0 0 0 0 0
0 0 1 6 3 0 0 0 0 0
0 0 0 4 4 4 0 0 0 0
0 0 0 0 2 3 2 0 0 0
0 0 0 0 0 2 6 2 0 0
0 0 0 0 0 0 4 2 2 0
0 0 0 0 0 0 0 3 3 1
0 0 0 0 0 0 0 0 3 3
这利用了implicit expansion, as well as sparse
to add values at coincident indices, and (:)
indexing to linearize a matrix in the usual column-major order。
ind1 = repmat((1:n).', n, 1) + (0:N-n); % column indices for the sum
ind2 = repelem((1:n).', n) + (0:N-n); % row indices for the sum
M = full(sparse(ind1(:), ind2(:), deepMiniM(:), N, N)); % sum over those indices