Preston Little
Preston Little

Reputation: 9

Multiply matrices in Java

I think I'm missing something small but I can't tell what it might be. I'm trying to create a method that will multiply two matrices. I'm also trying to only use 2 for loops in my method instead of 3.

For example, if I input

{1, 2, 3},
{2, 5, 6}

and

{4, 5},
{3, 2},
{1, 1}

I should get

{13, 12},
{29, 26}

But I end up getting

{5, 12, 3},
{8, 15, 6}

Above this method, I have instance variables 'private in numRows' and 'private int numColumns' to set the dimensions of the matrix. I have another instance variable 'private int data[][]' that's the internal storage of the matrix elements. Then I have a Constructor for a new Matrix that automatically determines dimensions.

I've tried swapping i's and j's and data.length for numRows/numColumns but I'm stuck at this point. Any suggestions?

public Matrix(int d[][]) {
        // d.length is the number of 1D arrays in the 2D array
        numRows = d.length;
        if (numRows == 0)
            numColumns = 0;
        else
            numColumns = d[0].length; // d[0] is the first 1D array

        // create a new matrix to hold the data
        data = new int[numRows][numColumns];

        // copy the data over
        for (int i = 0; i < numRows; i++)
            for (int j = 0; j < numColumns; j++)
                data[i][j] = d[i][j];
    }

public Matrix times(Matrix m) throws IllegalArgumentException {
        Matrix m2 = this;
        if (m.numRows != m2.numColumns)
            throw new IllegalArgumentException("Matrix information isn't correct");

        Matrix newArray = new Matrix(data);
        for (int i = 0; i < data.length; i++)
            for (int j = 0; j < data.length; j++)
                newArray.data[i][j] += m.data[i][j] * m2.data[j][i];

        return newArray;
    }

Upvotes: 0

Views: 548

Answers (1)

abdo Salm
abdo Salm

Reputation: 1841

first of all , not enough information is provided in your example . so I made my own example where

matrix1 =

1 2 3 
4 5 6

and matrix2 =

7  8
9  10
11 12

so the result =

58   64
139  154

also made a function called printMatrix() to help debugging and printing the matrix, also this line has a great problem Matrix newArray = new Matrix(data); , as data represents the first matrix , so you are making a new matrix which have the same dimensions as the first matrix which is incorrect;

if matrix1 is of dimension 2 x 3 and matrix2 is of dimension 3 x 2 then the result matrix dimension must be of size 2 x 2 not 2 x 3. so that's a problem in your code, also there is no way that you can do it with only 2 for loops , you will need a third for loop to help you iterate through the whole matrix and put it in the result and this is full code :

class Matrix:

public class Matrix
{
    private int numRows;
    private int numColumns;
    private int data[][];

    public Matrix(int d[][]) {

        // d.length is the number of 1D arrays in the 2D array
        numRows = d.length;
        if (numRows == 0)
            numColumns = 0;
        else
            numColumns = d[0].length; // d[0] is the first 1D array

        // create a new matrix to hold the data
        data = new int[numRows][numColumns];

        // copy the data over
        for (int i = 0; i < numRows; i++)
            for (int j = 0; j < numColumns; j++)
                data[i][j] = d[i][j];
    }

    public Matrix times(Matrix m) throws IllegalArgumentException {
        Matrix m2 = this;
        if (m.numRows != m2.numColumns)
            throw new IllegalArgumentException("Matrix information isn't correct");

        int tempM[][] = new int[data.length][m.data[0].length];
        for (int i = 0; i < data.length; i++)       // a row
            for (int j = 0; j < m.data[0].length; j++)       // b column
                for (int k = 0; k < data[0].length; k++)      // multiplication and sum iterator
                    tempM[i][j] += m2.data[i][k] * m.data[k][j];

        return new Matrix(tempM);
    }

    public void printMatrix() {
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[0].length; j++) {
                System.out.print(data[i][j] + " ");
            }
            System.out.println();
        }
    }
}

and here is the main I used to test the code:

public class Main
{
    public static void main(String[] args) {
        int m1[][] = {{1, 2, 3}, {4, 5, 6}};
        int m2[][] = {{7, 8}, {9, 10}, {11, 12}};

        Matrix matrix1 = new Matrix(m1);
        Matrix matrix2 = new Matrix(m2);

        Matrix result = matrix1.times(matrix2);
        result.printMatrix();

    }
}

Upvotes: 1

Related Questions