沿大矩阵对角线插入2x2矩阵的代码的矢量化 [英] Vectorisation of code for insertion of 2x2 matrix along the diagonal of a large matrix

查看:102
本文介绍了沿大矩阵对角线插入2x2矩阵的代码的矢量化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试沿着大矩阵(例如10x10)的对角线对小矩阵(2x2)进行元素插入.将添加重叠值,并且仅在小矩阵完全适合大矩阵的位置插入小矩阵.

I am trying to do an elementwise insertion of a small matrix (2x2) along the diagonal of a large matrix (10x10 say). Overlapping values are added, and the small matrix is only inserted where it can fit fully inside the large matrix.

我已经使用for循环实现了这一点,但很好奇该过程是否可以向量化.

I have achieved this using a for loop, but am curious whether the process can be vectorised.

function M = TestDiagonal()

N     = 10;
miniM = [1, -1; -1, 1];
M     = zeros(N);

for i = 1:N-1
    M(i:i+1,i:i+1) = M(i:i+1,i:i+1) + miniM;
end

end

提供所需的矩阵

 1    -1     0     0     0     0     0     0     0     0
-1     2    -1     0     0     0     0     0     0     0
 0    -1     2    -1     0     0     0     0     0     0
 0     0    -1     2    -1     0     0     0     0     0
 0     0     0    -1     2    -1     0     0     0     0
 0     0     0     0    -1     2    -1     0     0     0
 0     0     0     0     0    -1     2    -1     0     0
 0     0     0     0     0     0    -1     2    -1     0
 0     0     0     0     0     0     0    -1     2    -1
 0     0     0     0     0     0     0     0    -1     1

在一般情况下,输入将始终为正方形,但可以采用任何大小.步长将始终等于1.

In the general case, the input will always be square, but can take any size. The step dimension will always be equal to 1.

推荐答案

只需使用2D卷积(请参见 conv2 ).

Just use 2D convolution (see conv2).

M = conv2(eye(N-1), miniM);

m×m情况,沿每个维度的第1步

m×m case, step 1 along each dimension

M = conv2(eye(N-size(miniM-1)+1), miniM);

m×n情况,沿每个维度的任意步长

在这种情况下,需要定义步骤:

m×n case, arbitrary steps along each dimension

In this case the steps need to be defined:

step = [2 1]; % desired step along each dimension

,并且定义所需的重复次数R而不是最终大小(N)更有意义,因为使用miniM的完整重复可能无法实现最终大小:

and it makes more sense to define a desired number of repetitions R, rather than the final size (N), because the latter may not be achievable with full repetitions of miniM:

R = 4; % desired number of repetitions

然后:

M = conv2(full(sparse(1:step(1):step(1)*R, 1:step(2):step(2)*R, 1)), miniM);

示例:

>> miniM = [10 20 30; 40 50 60];
>> R = 4;
>> step = [1 2];
>> M = conv2(full(sparse(1:step(1):step(1)*R, 1:step(2):step(2)*R, 1)), miniM)
M =
    10    20    30     0     0     0     0     0     0
    40    50    70    20    30     0     0     0     0
     0     0    40    50    70    20    30     0     0
     0     0     0     0    40    50    70    20    30
     0     0     0     0     0     0    40    50    60

这篇关于沿大矩阵对角线插入2x2矩阵的代码的矢量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆