MATLAB: Matrix dimension must agree

I want to extract the image boundary using erosion without using builtin-function.
a=imread('image')
p=size(a)
w=[1 1 1;1 1 1;1 1 1];
for x=2:1:p(1)-1
for y=2:1:p(2)-1
a1=[w(1)*a(x-1,y-1) w(2)*a(x-1,y) w(3)*a(x-1,y+1) w(4)*a(x,y-1) w(5)*a(x,y) w(6)*a(x,y+1) w(7)*a(x+1,y-1) w(8)*a(x+1,y) w(9)*a(x+1,y+1)];
A2(x,y)=min(a1);
end
end
figure(1),imshow(A2);
figure(2),boundary_extract=imshow(a-A2);
First erosion worked. but when I want to extract boundary using erosion, it says matrix dimensions must agree.

Best Answer

You do not initialize A2, and you only write up to p(1)-1 or p(2)-1 which is one row and one column smaller. Therefore A2 is smaller than a and you cannot subtract a-A2
You could probably rewrite your code using nlfilter()
Related Question