MATLAB Answers

## built-in 2D convolution vs for-loop convolution differences?

Asked by Matthew Lang

### Matthew Lang (view profile)

on 8 May 2013
Accepted Answer by Iman Ansari

### Iman Ansari (view profile)

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');
```

## 1 Answer

### Iman Ansari (view profile)

Answer by Iman Ansari

### Iman Ansari (view profile)

on 8 May 2013
Accepted answer

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');
```

Matthew Lang

### Matthew Lang (view profile)

on 8 May 2013

Ahh! Perfect! Thank you.

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

New to MATLAB?