MATLAB: Do I get an error for the erosion code of an image

erodeerosionImage Processing Toolboxmorphology

My code is having an error, but I do not know where it is coming from. Thanks in advance!
function [img_out] = myErosion(img_in, N)
if img_in >=(2*N+1)^2
for k=0:N
for i=1:img_in(1)
for j=1:img_in(2)
if img_in(i+k,j)== 0
if img_in(i-k,j)== 0
if img_in(i,j+k)== 0
if img_in(i,j-k)== 0
if img_in(i+k,j+k)== 0
if img_in(i+k,j-k)== 0
if img_in(i-k,j+k)== 0
if img_in(i-k,j-k)== 0
img_out(i,j) = 0;
end
end
end
end
end
end
end
end
end
end
end
end
end

Best Answer

Again, you're just not thinking this through. Erosion is a local min. So do that instead of whatever you're trying to do. Try this: (untested)
[rows, columns] = size(img_in);
% N is an odd number that is the window size
n2 = floor(N/2);
img_out = zeros(size(img_in));
for c = n2 : columns - n2
for r = n2 : rows - n2
subImage = img_in(r-n2:r+n2, c-n2 : c+n2);
img_out(r, c) = min(subImage(:));
end
end