Search code examples
javaneural-network

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException ArrayIndexOutOfExceptions in multiplying two matrices


Trying to implement Neural Network in java and getting the above error, I have tried and googled a lot but I'm not able to get any solution. Driver class:

public class Driver {
    static double [][]X ={
            {0, 0},
            {1, 0},
            {0, 1},
            {1, 1}
    };
    static double [][] Y = {
            {0},{1},{1},{0}
    };

    public static void main(String[] args) {

        NNMain nn = new NNMain(2,10,1); // 2,10,1

        List<Double> output;

        nn.fit(X, Y, 50000);  

        double [][] inputMatrix = {  
                {0,0},{0,1},{1,0},{1,1}
        };
        for(double d[]:inputMatrix)
        {
            output = nn.predict(d);
            System.out.println(output.toString());
        }

The error is occurring while trying to multiply two matrices:

    public static Matrix multiply(Matrix a, Matrix b) {
        Matrix temp = new Matrix(a.r, a.c);
        for (int i = 0; i < temp.r; i++)
        {
            for (int j = 0; j < temp.c; j++) {
    
                double sum=0;
                for(int k=0; k < a.c; k++)
                {
                    sum  += a.data[i][k] * b.data[k][j];  // ERROR HERE
                }
                temp.data[i][j]=sum;
            }
        }
        return temp;
    }

Here the fit method is calling multiply function which is defined above in another file. I have tried changing the for loop conditions <= 0 or 1 but I'm unable to get this working.


Solution

  • Are you sure a’s column count (a.c) is always equal to b’s row count (b.r) which is a condition for matrix multiplication?