Hey all, I ended up getting the script to do what I needed to do. Here is my final result (that works).
clc;
clear;
format compact;
% Image importing
fname = uigetfile('.bmp','Pick the file');
A = imread(fname);
[m,n,p] = size(A);
B = A;
figure(1)
image(A)
for k = [1:p];
for j = [1:n];
for i = [1:m];
Y = B(i,j,k);
if Y == 0 | Y == 255;
if i == 1 & j == 1; % top left corner
Z = [(B(i, j+1)),(B(i+1,j)),(B(i+1,j+1))];
B(i,j,k) = median(Z);
elseif i == 1 & j > 1 & j < n; %top side
Z = [(B(i, j-1)),(B(i,j+1)),(B(i+1,j-1)),(B(i+1,j)),(B(i+1,j+1))];
B(i,j,k) = median(Z);
elseif i == 1 & j == n; % top right corner
Z = [(B(i, j-1)),(B(i+1,j-1)),(B(i+1,j))];
B(i,j,k) = median(Z);
elseif i > 1 & i < m & j == 1; % left side
Z = [(B(i-1, j)),(B(i-1,j+1)),(B(i,j+1)),(B(i+1,j)),(B(i+1,j+1))];
B(i,j,k) = median(Z);
elseif i > 1 & i < m & j == n; % right side
Z = [(B(i-1, j-1)),(B(i-1,j)),(B(i,j-1)),(B(i+1,j-1)),(B(i+1,j))];
B(i,j,k) = median(Z);
elseif i == m & j == 1; %bottom left corner
Z = [(B(i-1, j)),(B(i-1,j+1)),(B(i,j+1))];
B(i,j,k) = median(Z);
elseif i == m & j > 1 & j < n; %bottom side
Z = [(B(i-1, j-1)),(B(i-1,j)),(B(i-1,j+1)),(B(i,j-1)),(B(i,j+1))];
B(i,j,k) = median(Z);
elseif i == m & j == n; %bottom right corner
Z = [(B(i-1, j-1)),(B(i-1,j)),(B(i,j-1))];
B(i,j,k) = median(Z);
elseif i > 1 & i < m & j > 1 & j < n; %every other position
Z = [(B(i-1, j-1)),(B(i-1,j)),(B(i-1,j+1)),(B(i,j-1)),(B(i,j+1)),(B(i,j-1)),(B(i,j+1)),(B(i+1,j-1)),(B(i+1,j)),(B(i+1,j+1))];
B(i,j,k) = median(Z);
end
end
end
end
end
figure(2)
image(B)
fnameo = uiputfile('.bmp','Insert desired output filename');
imwrite(B,fnameo);