Search code examples
javamultidimensional-arraymatrix-multiplication

Matrix multiply in Java


I created a function to multiply a matrix by itself which gets 2 parameters, one is the matrix, the other one is an int n. The problem is that I cant figure out where should I use the n in my code so that it multiplies the matrix by itself an n number of times (in other words matrix^n). At current stage it only does matrix^2;

public static int[][] lungimeDrumuri(int[][] array, int n) {
    int[][] newArray = new int[array.length][array.length];
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            int sum = 0;
            for (int x = 0; x < array.length; x++) {
                sum += array[i][x] * array[x][j];
            }
            newArray[i][j] = sum;
        }
    }
    return newArray;
}

Solution

  • Add a third for loop that goes from 1 < k < n . You will need to remain array untouched in order to maintain the values of the initial matrix, will also need a matrix newArray to keep the values of the previous multiplication and a temporary matrix tmp that just hold values during the multiplication itself and then is copied to newArray. Take a look in the sample below.

    FULL CODE

    public static int[][] lungimeDrumuri(int[][] array, int n) {
        int[][] newArray = new int[array.length][array.length];
        // Just holds values during multiplication between two matrices
        int[][] tmp = new int[array.length][array.length];
        
        // Initialize newArray to be equal to array
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length; j++) {
                newArray[i][j] = array[i][j];
            }
        }
    
        // Outer loop that multiplies as many times as you want
        for (int k = 1; k < n; k++) {
            for (int i = 0; i < array.length; i++) {
                for (int j = 0; j < array.length; j++) {
                    int sum = 0;
                    for (int x = 0; x < array.length; x++) {
                        sum += newArray[i][x] * array[x][j]; // Use newArray here
                    }
                    tmp[i][j] = sum;
                }
            }
            // Copy the result from multiplication to newArray and restart tmp
            System.arraycopy(tmp, 0, newArray, 0, tmp.length);
            tmp = new int[array.length][array.length];
        }
    
        return newArray;
    }
    

    Hope it helped!