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.
3 次查看(过去 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
0 个评论
回答(1 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Spectral Measurements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!