approximate derivative of matrix

The assignment question is: "Approximate the derivative of a matrix with respect to X"

Using this formula to create a new matrix from the original int[][] m:

m′[i][j] = (m[i−1][j +1]−m[i−1][j −1])+2∗(m[i][j +1]−m[i][j −1])+(m[i+1][j +1]−m[i+1][j −1]

Also, boundary cases (ex: m[0][0]) must be treated differently. For example, if the formula says to take m[-1][0], you should use the value for m[0][0] instead.

This is the code i have written so far:

public static int[][] approximateDerivativeX(int[][] m) {

int h = m.length;

int w = m[0].length;

int[][] derivativeXArray = new int[h][w];

for (int i=0; i < h; i++) {

for (int j=0; j < w; j++) {

if (i==0 && j==0) {

derivativeXArray[i][j] = 2*(m[i][j+1]-m[i][j]);

}

else if (i==0 && j!=0 && j < w-1) {

derivativeXArray[i][j] = (m[i][j+1]-m[i][j-1]) + 2*(m[i][j+1]-m[i][j-1]) + (m[i+1][j+1]-m[i+1][j-1]);

}

else if (i==0 && j==w-1) {

derivativeXArray[i][j] = (m[i][j]-m[i][j-1]) + 2*(m[i][j]-m[i][j-1]) + (m[i+1][j]-m[i+1][j-1]);

}

else if (i!=0 && i < h-1 && j==0) {

derivativeXArray[i][j] = (m[i-1][j+1]-m[i-1][j]) + 2*(m[i][j+1]-m[i][j]) + (m[i+1][j+1]-m[i+1][j]);

}

else if (i!=0 && i < h-1 && j!=0 && j < w-1) {

derivativeXArray[i][j] = (m[i-1][j+1]-m[i-1][j-1]) + 2*(m[i][j+1]-m[i][j-1]) + (m[i+1][j+1]-m[i+1][j-1]);

}

else if (i!=0 && i < h-1 && j==w-1) {

derivativeXArray[i][j] = (m[i-1][j]-m[i-1][j-1]) + 2*(m[i][j]-m[i][j-1]) + (m[i+1][j]-m[i+1][j-1]);

}

else if (i==h-1 && j==0) {

derivativeXArray[i][j] = (m[i-1][j+1]-m[i-1][j]) + 2*(m[i][j+1]-m[i][j]) + (m[i][j+1]-m[i][j]);

}

else if (i==h-1 && j!=0 && j < w-1) {

derivativeXArray[i][j] = (m[i-1][j+1]-m[i-1][j-1]) + 2*(m[i][j+1]-m[i][j-1]) + (m[i][j+1]-m[i][j-1]);

}

else if (i==h-1 && j==w-1) {

derivativeXArray[i][j] = (m[i-1][j]-m[i-1][j-1]) + 2*(m[i][j]-m[i][j-1]) + (m[i][j]-m[i][j-1]);

}

}

}

return derivativeXArray;

}

If the original matrix is this:

7 2 2 5 5

8 8 1 1 4

8 4 1 8 0

0 9 8 6 2

3 1 5 3 1

Then the derivative with respect to x should be:

-10 -17 -1 9 3

-9 -26 -7 8 -2

1 -13 -2 -5 -17

12 11 0 -17 -18

5 12 1 -14 -8

But the output I am getting is:

-10 -22 2 12 3

-9 -26 -7 8 -2

1 -13 -2 -5 -17

12 11 0 -17 -18

3 14 3 -18 -10

Any insight in what I am doing wrong?