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.
2 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Jan
on 6 Jul 2021
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 Comments
See Also
Categories
Find more on Spectral Measurements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!