Arrays 基于matlab的二维卷积矢量化

Arrays 基于matlab的二维卷积矢量化,arrays,matlab,loops,vectorization,convolution,Arrays,Matlab,Loops,Vectorization,Convolution,我得到了这段代码,用于计算两个给定数组的二维卷积 [r,c] = size(x); [m,n] = size(y); h = rot90(y, 2); center = floor((size(h)+1)/2); Rep = zeros(r + m*2-2, c + n*2-2); return for x1 = m : m+r-1 for y1 = n : n+r-1 Rep(x1,y1) = x(x1-m+1, y1-n+1); end end B = zeros(r+m-1,n

我得到了这段代码,用于计算两个给定数组的二维卷积

[r,c] = size(x);
[m,n] = size(y);
h = rot90(y, 2);
center = floor((size(h)+1)/2);
Rep = zeros(r + m*2-2, c + n*2-2);
return

for x1 = m : m+r-1
for y1 = n : n+r-1
    Rep(x1,y1) = x(x1-m+1, y1-n+1);
end
end

B = zeros(r+m-1,n+c-1);
for x1 = 1 : r+m-1
for y1 = 1 : n+c-1
    for i = 1 : m
        for j = 1 : n
            B(x1, y1) = B(x1, y1) + (Rep(x1+i-1, y1+j-1) * h(i, j));
        end
    end
end
end
如何将其矢量化,从而不存在for循环?
提前感谢。

以下是我的想法:

%// generate test matrices
x = randi(12, 4, 5)
y = [2 2 2;
     2 0 2;
     2 2 2]

[r,c] = size(x);
%[m,n] = size(y);   %// didn't use this
h = rot90(y, 2);
center = floor((size(h)+1)/2);

Rep = zeros(size(x)+size(h)-1);                             %// create image of zeros big enough to pad x
Rep(center(1):center(1)+r-1, center(2):center(2)+c-1) = x;  %// and copy x into the middle

%// all of this can be compressed onto one line, if desired
%// I'm just breaking it out into steps for clarity
CRep = im2col(Rep, size(h), 'sliding');   %// 'sliding' is the default, but just to be explicit
k = h(:);                                 %// turn h into a column vector
BRow = bsxfun(@times, CRep, k);           %// multiply k times each column of CRep
B = reshape(sum(BRow), r, c)              %// take the sum of each column and reshape to match x

T = conv2(Rep, h, 'valid')                %// take the convolution using conv2 to check

assert(isequal(B, T), 'Result did not match conv2.');
以下是示例运行的结果:

x =

   11   12   11    2    8
    5    9    2    3    2
    7    9    3    4    8
    7   10    8    5    4

y =

   2   2   2
   2   0   2
   2   2   2

B =

    52    76    56    52    14
    96   120   106    80    50
    80   102   100    70    36
    52    68    62    54    34

T =

    52    76    56    52    14
    96   120   106    80    50
    80   102   100    70    36
    52    68    62    54    34

这和你的有什么不同?在上一篇文章中,我试图更一般化,不显示所有的代码。请不要打开重复的问题。如果您想澄清一些问题,请将新信息编辑到现有问题中。确定。我将删除前面的问题。你知道如何实现这种矢量化吗?第一个循环只是用零填充输入数组,对吗?我不确定我是否理解你的数学。对于第二个循环,我们可以使用
im2col
。我会让那部分工作并检查我的代码。