built-in 2D convolution vs for-loop convolution differences?
4 views (last 30 days)
Show older comments
Matthew Lang
on 8 May 2013
Commented: Burak Karadeniz
on 20 Mar 2021
Can someone tell me what's up with the following code? Why do I get different results implementing my own convolution w/ for loops vs the conv2 function?
x = 0:.1:pi;
A = rand(100,100);
M = sin(x).^2'*sin(x).^2;
figure(1);
subplot(3,2,1);imagesc(x,x,M);colorbar('vert');title('Convolution kernel');
subplot(3,2,2);imagesc(A);colorbar('vert');title('Data matrix');
res = conv2(A,M,'valid');
subplot(3,2,3);imagesc(res);colorbar('vert');title('conv2(A,M)');
res2 = zeros(size(res));
for ii = 1:size(A,1)-size(M,1)+1
for jj = 1:size(A,2)-size(M,2)+1
res2(ii,jj) = sum(sum(M.*A(ii:ii+size(M,1)-1,jj:jj+size(M,2)-1)));
end
end
subplot(3,2,4);imagesc(res2);colorbar('vert');title('for loop conv2(A,M)');
subplot(3,2,5);imagesc(res-res2);colorbar('vert');title('difference');
subplot(3,2,6);imagesc(100*(res-res2)./res);colorbar('vert');title('% error');
0 Comments
Accepted Answer
Iman Ansari
on 8 May 2013
Hi. You need to rotate your kernel 180 degree:
x = 0:.1:pi;
A = rand(100,100);
M = sin(x).^2'*sin(x).^2;
figure(1);
subplot(3,2,1);imagesc(x,x,M);colorbar('vert');title('Convolution kernel');
subplot(3,2,2);imagesc(A);colorbar('vert');title('Data matrix');
res = conv2(A,M,'valid');
subplot(3,2,3);imagesc(res);colorbar('vert');title('conv2(A,M)');
res2 = zeros(size(res));
M=rot90(M,2);
for ii = 1:size(A,1)-size(M,1)+1
for jj = 1:size(A,2)-size(M,2)+1
res2(ii,jj) = sum(sum(M.*A(ii:ii+size(M,1)-1,jj:jj+size(M,2)-1)));
end
end
subplot(3,2,4);imagesc(res2);colorbar('vert');title('for loop conv2(A,M)');
subplot(3,2,5);imagesc(res-res2);colorbar('vert');title('difference');
subplot(3,2,6);imagesc(100*(res-res2)./res);colorbar('vert');title('% error');
2 Comments
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!