Skip to content
Advertisement

Matrix multiplication in Java using 2D ArrayLists

I am trying to implement a simple matrix multiplication in Java, where I am storing the matrices in two-dimensional ArrayLists. It would seem the error is caused by the setting of matrix Result, inside the nested for loop, but I do not understand why.

JavaScript

The code produces the result:

JavaScript

when in fact it should be:

JavaScript

Advertisement

Answer

The Result is incorrectly initialized.

JavaScript

This creates a matrix where two rows (or columns, depending how you look at that) are in fact same row (column), referenced twice.

You can init Result like that:

JavaScript
Advertisement