首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于matlab的二维卷积矢量化

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

Stack Overflow用户
提问于 2016-04-16 22:27:39
回答 1查看 1.2K关注 0票数 2

我得到了计算两个给定阵列的二维卷积的代码。

代码语言:javascript
复制
[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循环了?提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-17 14:59:27

我想出的是:

代码语言:javascript
复制
%// 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.');

下面是一个示例运行的结果:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36670510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档