You have to ensure that the indices are always valid, i.e., between 1 and the maximum number of rows / columns. For example, what is the output for row = 1, col = 1? In your implementation, you try to get frame(0, 0) in this case, which does not work.
You can use something like
frame(min(1, x - 1), min(1, y - 1))
frame(max(size(frame, 1), x +1, max(size(frame, 2), y + 1))
and accordingly for all instances where you refer to x/y +/- 1.
Please not that the first index into a matrix is the row that runs from top to bottom. Using variable named 'x' is bit misleading.