MATLAB: “Index exceeds matrix dimensions.” But it doesn’t

image processingmatrix

Masks=[0 1 0;...
1 -4 1;...
0 1 0;];
a=imread('C:\Users\***\Desktop\Matlab\figure\Fig3.40(a).jpg');
x=size(a);
m=x(1,1);
n=x(1,2);
b(m,n)=0;
Newres=uint8(b);
for i=1:m
for j=1:n
if i==1 && j==1
Newres(i,j)=Masks(2,2)*a(i,j)+Masks(2,3)*a(i,j+1)+Masks(3,2)*a(i+1,j)+Masks(3,3)*a(i+1,j+1);
elseif i==1 && 1<j<=n-1
Newres(i,j)=Masks(2,1)*a(i,j-1)...
+Masks(2,2)*a(i,j)...
+Masks(2,3)*a(i,j+1)... %%<-----Line 18
+Masks(3,1)*a(i+1,j-1)...
+Masks(3,2)*a(i+1,j)+Masks(3,3)*a(i+1,j+1); %%<--------Line 20
elseif i==1 && j==n
Newres(i,j)=Masks(2,1)*a(i,j-1)...
+Masks(2,2)*a(i,j)...
+Masks(3,1)*a(i+1,j-1)...
+Masks(3,2)*a(i+1,j);
elseif 1<i<=m-1 && j==1
Newres(i,j)=Masks(1,2)*a(i-1,j)...
+Masks(1,3)*a(i-1,j+1)+Masks(2,2)*a(i,j)...
+Masks(2,3)*a(i,j+1)+Masks(3,2)*a(i+1,j)+Masks(3,3)*a(i+1,j+1); %%<--- Line 29
elseif 1<i<=m-1 && j==n
Newres(i,j)=Masks(1,1)*a(i-1,j-1)...
+Masks(1,2)*a(i-1,j)+Masks(2,1)*a(i,j-1)...
+Masks(2,2)*a(i,j)+Masks(3,1)*a(i+1,j-1)+Masks(3,2)*a(i+1,j); %%<---- Line 33
elseif i==m && j==1
Newres(i,j)=Masks(1,2)*a(i-1,j)...
+Masks(1,3)*a(i-1,j+1)...
+Masks(2,2)*a(i,j)+Masks(2,3)*a(i,j+1);
elseif i==m && 1<j<=n-1
Newres(i,j)=Masks(1,1)*a(i-1,j-1)+Masks(1,2)*a(i-1,j)...
+Masks(1,3)*a(i-1,j+1)+Masks(2,1)*a(i,j-1)...
+Masks(2,2)*a(i,j)+Masks(2,3)*a(i,j+1);
elseif i==m && j==n
Newres(i,j)=Masks(1,1)*a(i-1,j-1)...
+Masks(1,2)*a(i-1,j)...
+Masks(2,1)*a(i,j-1)+Masks(2,2)*a(i,j);
else
Newres(i,j)=Masks(1,1)*a(i-1,j-1)+Masks(1,2)*a(i-1,j)...
+Masks(1,3)*a(i-1,j+1)+Masks(2,1)*a(i,j-1)+...
Masks(2,2)*a(i,j)+Masks(2,3)*a(i,j+1)+...
Masks(3,1)*a(i+1,j-1)+Masks(3,2)*a(i+1,j)+...
Masks(3,3)*a(i+1,j+1);
end
if Newres(i,j)>255
Newres(i,j)=0;
end
end
end
This is a code for image processing. When I run it, it says Index exceeds matrix dimensions. for line 18. When I make a(i,j), this time line 20 gives the same error. On line 20 I turn (j+1) to j and then matlab says line 29. There I turn i+1 to i. And line 33 gives the exact same error. The promblem is matrix dimensions are not exceeded. If you use
for k=1:n-1 a(1,k+1)
end
on your command window you will get results.
So why is this happening?
To better understand me use any image on your computer.

Best Answer

You set m and n to size() of the image. You have for j=1:n . Your loop tries to index the image a(i,j+1) . But when j reaches n in the loop, reaches the number of columns in the image, then a(i,j+1) tries to go one past the number of columns.