MATLAB: Index out of bounds

index bounds

hello, i want to use canny edge detection from this image
here is the code :
handles.m = edge(handles.m,'canny');
[h, w] = size(handles.m);
filter = [0.0174 0.348 0.04348 0.0348 0.0174; 0.0348 0.0782 0.1043 0.0782 0.0348; 0.0435 0.1043 0.1304 0.1043 0.0435;0.0348 0.0782 0.1043 0.0782 0.0348; 0.0174 0.348 0.04348 0.0348 0.0174];
Mx = [-1 0 1; -2 0 2; -1 0 1];
My = [-1 -2 -1; 0 0 0; 1 2 1];
for v = 2 : 511
for u = 2 : 511
sum = 0;
for i = -2 : 2
for j = -2 : 2
sum = sum + (handles.m(u, v) * filter(i+3, j+3));
end
end
handles.mx(u,v) = sum;
end
end
guidata(hObject,handles);
axes(handles.axes3);
imshow(handles.m);
msgbox('Detection SUCCESSFUL !');
when i execute the program, an error occured like this :
??? Attempted to access handles.m(139,2); index out of bounds because
size(handles.m)=[138,1130].
Error in ==> processing>pushbutton12_Callback at 247
sum = sum + (handles.m(u, v) * filter(i+3, j+3));
anyone knows why? Thanks

Best Answer

Because your m matrix does not have 139 rows in it. It has only 138 rows. The error message plainly says this. We do not know why it has only 138 rows, nor do we know why you are trying to access rows beyond that.
Possible fix:
[rows, columns] = size(handles.m);
for v = 2 : columns - 1
for u = 2 : rows - 1
Also, do not use sum as a variable name because it's a built-in function.