How can i make a 2D convolution with x = [1 0 2; -1 3 1; -2 4 0] and h = [1 -1; 0 2] and not use conv2? Can you please help me.

7 次查看(过去 30 天)
I wanted to write a 2D convolution without conv2 where x = [1 0 2; -1 3 1; -2 4 0] and h = [1 -1; 0 2] but i get the wrong result of y=[7 0; 4 2] with the following code, can you help me?
m = 0:.1:pi;
x = [1 0 2; -1 3 1; -2 4 0];
h = [1 -1; 0 2];
res = conv2(x,h,'valid');
y = zeros(size(res));
for ii = 1:size(x,1)-size(h,1)+1
for jj = 1:size(x,2)-size(h,2)+1
y(ii,jj) = sum(sum(h.*x(ii:ii+size(h,1)-1,jj:jj+size(h,2)-1)));
end
end

回答(1 个)

Jan
Jan 2021-7-6
Look at the definition of the convolution again.
Either the orientation of h or the submatrices of x must be changed:
[h1, h2] = size(h);
[x1, x2] = size(x)
% Either:
h = rot90(h, 2);
for ii = 1:x1 - h1 + 1
for jj = 1:x2 - h2 + 1
y(ii,jj) = sum(h .* x(ii:ii+h1-1, jj:jj+h2-1), 'all');
end
end
% Or:
for ii = 1:x1 - h1 + 1
for jj = 1:x2 - h2 + 1
y(ii,jj) = sum(h .* x(ii+h1-1:-1:ii, jj+h2-1:-1:jj), 'all');
end
end

类别

Help CenterFile Exchange 中查找有关 Oceanography and Hydrology 的更多信息

产品


版本

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by