Questions related to matrix multiplication, especially implementation. Mathematical questions should consider the [linear-algebra] tag.
Matrix multiplication is usually the process of multiplying two (or more) matrices. This arises quite frequently in linear algebra contexts and is a particularly fundamental task in computing, especially in scientific computing.
To that end, a number of fundamental libraries, such as LAPACK, BLAS, ATLAS, and others have been developed. Because the growth of matrices affects the computational time, extensive effort has been made to optimize these packages for various computer architectures and various matrix sizes.
In scientific software r for statistical computing and graphics, operator %*%
performs matrix multiplication (see ?"%*%"
), and interfaces BLAS routine dgemmm
.
The product of the multiplication of two matrices a
and b
is the matrix c
, where each element is the sum of the products of the i-th row of a
and the j-th column of b
.
c[i][j] += a[i][k] * b[k][j];
Example:
(b) { 1, 2, 3, 4}
{ 5, 6, 7, 8}
(a) ┌(c)──────────────
{1, 2} │ {11, 14, 17, 20}
{3, 4} │ {23, 30, 37, 44}
{5, 6} │ {35, 46, 57, 68}
Algorithm of the matrix multiplication:
// rows of 'a' matrix
int m = 3;
// columns of 'a' matrix
// and rows of 'b' matrix
int n = 2;
// columns of 'b' matrix
int p = 4;
// matrices 'a=m×n', 'b=n×p'
int[][] a = {{1, 2}, {3, 4}, {5, 6}},
b = {{1, 2, 3, 4}, {5, 6, 7, 8}};
// resulting matrix 'c=m×p'
int[][] c = new int[m][p];
// iterate over the rows of the 'a' matrix
for (int i = 0; i < m; i++) {
// iterate over the columns of the 'b' matrix
for (int j = 0; j < p; j++) {
// iterate over the columns of the 'a'
// matrix, aka rows of the 'b' matrix
for (int k = 0; k < n; k++) {
// sum of the products of
// the i-th row of 'a' and
// the j-th column of 'b'
c[i][j] += a[i][k] * b[k][j];
}
}
}