MATLAB: Having problem with error “index out of bounds” numel (Y)=1″

boundserrorImage Processing Toolboxindex

Hello all! I am trying to write a code that takes the noise out of bitmap images, and re-writes them as a cleaned image afterward. I'm not done with the code entirely yet, but my function file keeps spitting out the error
Attempted to access Y(8,1); index out of bounds because numel(Y)=1.
Error in fixp (line 13)
A = [(Y((i-1), j)),(Y((i-1),(j+1))),(Y(i,(j+1))),(Y((i+1),j)),(Y((i+1),(j+1)))];
Here is what my main file looks like:
clc;
clear;
format compact;
% Image importing
A = imread('J20_pic1_noisy.bmp');
[m,n,p] = size(A);
for k = [1:p];
for j = [1:n];
for i = [1:m];
Y = A(i,j,k);
if Y == 0 | Y == 255;
[B] = fixp(Y,i,j,m,n);
end
end
end
end
and here is what the function file looks like:
function[B] = fixp(Y,i,j,m,n);
B = [];
if i == 1 & j == 1 % top left corner
A = [(Y(i, j+1)),(Y(i+1,j)),(Y(i+1,j+1))];
B(i, j)= mean(median(A));
elseif i == 1 & j > 1 & j < n %top side
A = [(Y(i, j-1)),(Y(i,j+1)),(Y(i+1,j-1)),(Y(i+1,j)),(Y(i+1,j+1))];
B(i, j)= mean(median(A));
elseif i == 1 & j == n % top right corner
A = [(Y(i, j-1)),(Y(i+1,j-1)),(Y(i+1,j))];
B(i, j)= mean(median(A));
elseif i > 1 & i < m & j == 1 % left side
A = [(Y(i-1, j)),(Y(i-1,j+1)),(Y(i,j+1)),(Y(i+1,j)),(Y(i+1,j+1))];
B(i, j)= mean(median(A));
elseif i > 1 & i < m & j == n % right side
A = [(Y(i-1, j-1)),(Y(i-1,j)),(Y(i,j-1)),(Y(i+1,j-1)),(Y(i+1,j))];
B(i, j)= mean(median(A));
elseif i == m & j == 1 %bottom left corner
A = [(Y(i-1, j)),(Y(i-1,j+1)),(Y(i,j+1))];
B(i, j)= mean(median(A));
elseif i == m & j > 1 & j < n %bottom side
A = [(Y(i-1, j-1)),(Y(i-1,j)),(Y(i-1,j+1)),(Y(i,j-1)),(Y(i,j+1))];
B(i, j)= mean(median(A));
elseif i == m & j == n %bottom right corner
A = [(Y(i-1, j-1)),(Y(i-1,j)),(Y(i,j-1))];
B(i, j)= mean(median(A));
elseif i > 1 & i < m & j > 1 & j < n %every other position
A = [(Y(i-1, j-1)),(Y(i-1,j)),(Y(i-1,j+1)),(Y(i,j-1)),(Y(i,j+1)),(Y(i,j-1)),(Y(i,j+1)),(Y(i+1,j-1)),(Y(i+1,j)),(Y(i+1,j+1))];
B(i, j)= mean(median(A));
end
end
Does anyone know what is causing the error, and subsequently, how to fix it? Thank you!

Best Answer

You're going overall rows and all columns but trying to access a 3x3 window around it. What will happen if you are at the edge of an image? You'd have i or j = -1. There is no -1 row. Try going from i = 1:rows, and j = 2:columns.