Taskcore
Do matrix arithmetic
Also called matrix multiplication, multiply two matrices, matrix product, matrix transpose, transpose a matrix, 2D array, two-dimensional array, row-major order, column-major order, @ operator, matmul, zip(*m).
Multiply two matrices and transpose a matrix, with a list of rows. The columns of the first matrix must match the rows of the second, and a times b is not b times a.
- Evidence
- Code in 10 languages
Task
Multiply two matrices, and transpose a matrix. The Rosetta Code task says: "Multiply two matrices together"1. The matrices "can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix"1. The second task is: "Transpose an arbitrarily sized rectangular Matrix"2.
A matrix is a list of rows, and each row is a list of numbers. The function matrix_multiply(a, b) returns the product of a and b. If a has n rows and m columns, and b has m rows and p columns, the product has n rows and p columns. The item in row i and column j of the product is the sum of a[i][k] * b[k][j] for each k: row i of a times column j of b. For example:
[1 2] [5 6] [1*5 + 2*7 1*6 + 2*8] [19 22]
[3 4] x [7 8] = [3*5 + 4*7 3*6 + 4*8] = [43 50]
"For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix"3. The order is important: "the product is not commutative in general"3, so a times b is often not b times a.
The transpose of a matrix swaps the rows and the columns: row i of the transpose is column i of the matrix. Each solution also has a function transpose.
Solutions
| Language | Matrix | Transpose |
|---|---|---|
| Python | a list of lists, and zip(*b) for the columns |
zip(*m) |
| JavaScript, TypeScript | an array of arrays, with map and reduce |
map over the columns |
| Java | long[][], with three loops |
two loops |
| C# | a jagged array long[][], with three loops |
two loops |
| Go | [][]int64, with three loops |
two loops |
| Rust | slices of rows, and a Vec<Vec<i64>> result |
iterators |
| C | a flat array in row-major order, with three loops | two loops |
| C++ | std::vector<std::vector<long long>>, with three loops |
two loops |
| Bash | a string of rows, separated by ;, and a flat array |
loops |
- Python.
zip(*b)gives the columns ofb, because "zip() in conjunction with the * operator can be used to unzip a list"4. Then each item of the product issum(x * y for x, y in zip(row, col)). Python has the operator@for matrix multiplication: "This PEP proposes a new binary operator to be used for matrix multiplication, called @"5. But "No implementations of these methods are added to the builtin or standard library types"5, so@works on NumPy arrays and not on lists. - JavaScript. There is no matrix type.
a.mapmakes the rows of the product, androw.reducemakes each sum. The function checks the sizes first, as the pitfalls show. - TypeScript. The same functions as JavaScript, with the type
readonly (readonly number[])[]. - Java.
long[][]is an array of rows. The loops go in the orderi,k,j, so the inner loop reads a row ofb, not a column. - C#. A jagged array
long[][], with the same loops as Java.System.NumericshasMatrix3x2andMatrix4x4for graphics, withfloatitems and fixed sizes, so they do not fit this task. - Go.
[][]int64is a slice of rows.MatrixMultiplyreturns an error if the sizes do not match. - Rust. The standard library has no matrix type. The function accepts a slice of rows of any type that gives a
&[i64], and returnsNoneif the sizes do not match. The cratesnalgebraandndarrayhave matrix types. - C. The matrices are flat arrays in row-major order: the item in row
iand columnjof a matrix withmcolumns is at indexi * m + j. The caller gives the sizes. - C++.
std::vector<std::vector<long long>>holds the rows. The function throwsstd::invalid_argumentif the sizes do not match. - Bash. Bash has no two-dimensional arrays. A matrix is a string such as
"1 2;3 4", and the function puts the numbers in a flat array and uses the indexi * m + k.
The Python functions:
def transpose(m):
return [list(col) for col in zip(*m)]
def matrix_multiply(a, b):
cols = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
print(matrix_multiply(a, b))
print(matrix_multiply(b, a))
print(transpose([[1, 2, 3], [4, 5, 6]]))
[[19, 22], [43, 50]]
[[23, 34], [31, 46]]
[[1, 4], [2, 5], [3, 6]]
a times b and b times a are different. The Go function, with a 2 x 3 matrix and a 3 x 2 matrix. In the other order, the product is 3 x 3:
package main
import "fmt"
func multiply(a, b [][]int) [][]int {
c := make([][]int, len(a))
for i := range a {
c[i] = make([]int, len(b[0]))
for k, x := range a[i] {
for j, y := range b[k] {
c[i][j] += x * y
}
}
}
return c
}
func main() {
a := [][]int{{1, 2, 3}, {4, 5, 6}}
b := [][]int{{7, 8}, {9, 10}, {11, 12}}
fmt.Println(multiply(a, b))
fmt.Println(multiply(b, a))
}
[[58 64] [139 154]]
[[39 54 69] [49 68 87] [59 82 105]]
Row-major order. A two-dimensional array in C is one block of memory. "In row-major order, the consecutive elements of a row reside next to each other"6. "Row-major order is used in C/C++/Objective-C (for C-style arrays)"6, and "Row-major order is the default in NumPy"6. Fortran, MATLAB, Julia and R use column-major order6. The C program shows the order:
#include <stdio.h>
int main(void) {
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
const int *flat = &m[0][0];
for (int i = 0; i < 6; i++) {
printf("%d%c", flat[i], i == 5 ? '\n' : ' ');
}
printf("%d %d\n", m[1][2], flat[1 * 3 + 2]);
return 0;
}
1 2 3 4 5 6
6 6
The rows are next to each other, so m[1][2] is at index 1 * 3 + 2. A loop that reads the items in the order of memory is faster, because the processor loads the next items into the cache with each item. That is why the solutions use the loop order i, k, j.
Cost. The product of an n x m matrix and an m x p matrix takes n * m * p multiplications. For two square n x n matrices, the algorithm of the definition takes n * n * n multiplications, so its time is O(n³)3. Faster algorithms exist: Strassen's algorithm, from 1969, has a smaller exponent, about 2.8073. Numerical libraries also divide the matrices into blocks that fit in the cache, so they are much faster than three simple loops. The transpose takes one step for each item, n * m steps.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
two-by-two: the example above.two-by-three-times-three-by-two: two matrices that are not square. The product is 2 x 2.one-by-one: a matrix with one item. The product is the product of the two numbers.row-times-column: a 1 x 3 matrix times a 3 x 1 matrix gives a 1 x 1 matrix, the dot product.column-times-row: a 3 x 1 matrix times a 1 x 3 matrix gives a 3 x 3 matrix, the outer product.identity: the identity matrix timesbisb.other-order:btimesafor the matrices oftwo-by-two. The result is different.zero-matrix: the zero matrix times any matrix is the zero matrix.negative-numbers: items below 0, and a sum that is 0.beyond-32-bit: the item 10000000000 does not fit in 32 bits, so the solutions use 64-bit integers.
Pitfalls
- All rows are the same list. In Python,
[[0] * p] * nmakes one row andnreferences to it. "The reason is that replicating a list with * doesn’t create copies, it only creates references to the existing objects"7. Each write to a row writes to all rows:
This code runs but gives a wrong answer on purpose.
def matrix_multiply(a, b):
c = [[0] * len(b[0])] * len(a)
for i in range(len(a)):
for j in range(len(b[0])):
c[i][j] = sum(a[i][k] * b[k][j] for k in range(len(b)))
return c
print(matrix_multiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]))
[[43, 50], [43, 50]]
The result has the last row two times. Make a new list for each row: [[0] * p for _ in range(n)].
- No check of the sizes. If the number of columns of
ais not the number of rows ofb, the product is not defined. A loop with no check can return a wrong result and no error. In JavaScript,reducestops at the end of the row ofa, so it does not see the third row ofb:
This code runs but gives a wrong answer on purpose.
function matrixMultiply(a, b) {
return a.map((row) => b[0].map((_, j) => row.reduce((sum, x, k) => sum + x * b[k][j], 0)));
}
console.log(matrixMultiply([[1, 2]], [[1], [2], [3]]));
[ [ 5 ] ]
A 1 x 2 matrix times a 3 x 1 matrix has no product, but the function returns [5](/languages/all/#5). Check the sizes first, as the solutions do.
- The order of the matrices.
atimesbis notbtimesain general. When the two matrices are not square, one of the two products can be undefined, or the two products can have different sizes, as in the Go example. - Overflow. Each item of the product is a sum of
mproducts, so it can be much larger than the items ofaandb. With 32-bit integers, thebeyond-32-bitcase overflows. In C, a signed overflow is undefined behavior. - A jagged array is not a matrix. In Java, C#, Go and JavaScript, the rows are separate arrays, so they can have different lengths. The solutions read the length of the first row only. Check all rows if the input comes from outside the program.
- Column-major libraries. A library in Fortran order, such as a BLAS routine, reads a flat array as columns. A flat C array in row-major order is the transpose for such a library.
Related tasks
- Do complex number arithmetic: another task with a type that some languages do not have.
- Sum and multiply a list: each item of the product is the sum of the products of two lists.
- Use mathematical constants and functions: the other number functions of the standard libraries.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-matrix-arithmetic/.
def transpose(m: list[list[int]]) -> list[list[int]]:
"""Return the transpose of m: row i of the result is column i of m."""
return [list(col) for col in zip(*m)]
def matrix_multiply(a: list[list[int]], b: list[list[int]]) -> list[list[int]]:
"""Return the product a times b.
The number of columns of a must be the number of rows of b. Neither
matrix changes.
"""
if len(a[0]) != len(b):
raise ValueError(f"{len(a)}x{len(a[0])} times {len(b)}x{len(b[0])}: the sizes do not match")
cols = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]
test_matrix.py 38 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-matrix-arithmetic/.
import copy
import pytest
from matrix import matrix_multiply, transpose
CASES = [
("two-by-two", [[1, 2], [3, 4]], [[5, 6], [7, 8]], [[19, 22], [43, 50]]),
("two-by-three-times-three-by-two", [[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 10], [11, 12]], [[58, 64], [139, 154]]),
("one-by-one", [[3]], [[4]], [[12]]),
("row-times-column", [[1, 2, 3]], [[4], [5], [6]], [[32]]),
("column-times-row", [[1], [2], [3]], [[4, 5, 6]], [[4, 5, 6], [8, 10, 12], [12, 15, 18]]),
("identity", [[1, 0], [0, 1]], [[5, 6], [7, 8]], [[5, 6], [7, 8]]),
("other-order", [[5, 6], [7, 8]], [[1, 2], [3, 4]], [[23, 34], [31, 46]]),
("zero-matrix", [[0, 0], [0, 0]], [[1, 2], [3, 4]], [[0, 0], [0, 0]]),
("negative-numbers", [[-1, 2], [3, -4]], [[2, 0], [1, -1]], [[0, -2], [2, 4]]),
("beyond-32-bit", [[100000, 0], [0, 100000]], [[100000], [3]], [[10000000000], [300000]]),
]
@pytest.mark.parametrize(("name", "a", "b", "want"), CASES, ids=[c[0] for c in CASES])
def test_matrix_multiply(name, a, b, want):
before = copy.deepcopy((a, b))
assert matrix_multiply(a, b) == want
assert (a, b) == before
def test_transpose():
assert transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]]
assert transpose([[7]]) == [[7]]
def test_sizes_must_match():
with pytest.raises(ValueError):
matrix_multiply([[1, 2]], [[1, 2]])
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
#ifndef MATRIX_ARITHMETIC_HPP
#define MATRIX_ARITHMETIC_HPP
#include <cstddef>
#include <stdexcept>
#include <vector>
using Matrix = std::vector<std::vector<long long>>;
// Returns the transpose of m: row i of the result is column i of m.
inline Matrix transpose(const Matrix& m) {
Matrix t(m[0].size(), std::vector<long long>(m.size()));
for (std::size_t i = 0; i < m.size(); ++i) {
for (std::size_t j = 0; j < m[0].size(); ++j) {
t[j][i] = m[i][j];
}
}
return t;
}
// Returns the product a times b. Throws std::invalid_argument if the number
// of columns of a is not the number of rows of b.
inline Matrix matrix_multiply(const Matrix& a, const Matrix& b) {
if (a[0].size() != b.size()) {
throw std::invalid_argument("the sizes do not match");
}
Matrix c(a.size(), std::vector<long long>(b[0].size()));
for (std::size_t i = 0; i < a.size(); ++i) {
for (std::size_t k = 0; k < b.size(); ++k) {
for (std::size_t j = 0; j < b[0].size(); ++j) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
return c;
}
#endif
test_matrix.cpp 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
#include <cstdio>
#include <stdexcept>
#include "matrix.hpp"
namespace {
struct test_case {
const char* name;
Matrix a, b, want;
};
const test_case cases[] = {
{"two-by-two", {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}, {{19, 22}, {43, 50}}},
{"two-by-three-times-three-by-two", {{1, 2, 3}, {4, 5, 6}}, {{7, 8}, {9, 10}, {11, 12}}, {{58, 64}, {139, 154}}},
{"one-by-one", {{3}}, {{4}}, {{12}}},
{"row-times-column", {{1, 2, 3}}, {{4}, {5}, {6}}, {{32}}},
{"column-times-row", {{1}, {2}, {3}}, {{4, 5, 6}}, {{4, 5, 6}, {8, 10, 12}, {12, 15, 18}}},
{"identity", {{1, 0}, {0, 1}}, {{5, 6}, {7, 8}}, {{5, 6}, {7, 8}}},
{"other-order", {{5, 6}, {7, 8}}, {{1, 2}, {3, 4}}, {{23, 34}, {31, 46}}},
{"zero-matrix", {{0, 0}, {0, 0}}, {{1, 2}, {3, 4}}, {{0, 0}, {0, 0}}},
{"negative-numbers", {{-1, 2}, {3, -4}}, {{2, 0}, {1, -1}}, {{0, -2}, {2, 4}}},
{"beyond-32-bit", {{100000, 0}, {0, 100000}}, {{100000}, {3}}, {{10000000000LL}, {300000}}},
};
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
if (matrix_multiply(c.a, c.b) != c.want) {
std::printf("FAIL %s\n", c.name);
++failures;
}
}
if (transpose({{1, 2, 3}, {4, 5, 6}}) != Matrix{{1, 4}, {2, 5}, {3, 6}}) {
std::printf("FAIL transpose\n");
++failures;
}
try {
matrix_multiply({{1, 2}}, {{1, 2}});
std::printf("FAIL no exception\n");
++failures;
} catch (const std::invalid_argument&) {
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
/** Matrix arithmetic on arrays of rows. Java has no matrix type in the standard library. */
public final class MatrixArith {
private MatrixArith() {}
/** Returns the transpose of m: row i of the result is column i of m. */
public static long[][] transpose(long[][] m) {
long[][] t = new long[m[0].length][m.length];
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
t[j][i] = m[i][j];
}
}
return t;
}
/** Returns the product a times b. The number of columns of a must be the number of rows of b. */
public static long[][] multiply(long[][] a, long[][] b) {
int n = a.length;
int m = b.length;
int p = b[0].length;
if (a[0].length != m) {
throw new IllegalArgumentException("the sizes do not match");
}
long[][] c = new long[n][p];
// The order i, k, j reads b row by row, which is faster than column by column.
for (int i = 0; i < n; i++) {
for (int k = 0; k < m; k++) {
long x = a[i][k];
for (int j = 0; j < p; j++) {
c[i][j] += x * b[k][j];
}
}
}
return c;
}
}
MatrixArithTest.java 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class MatrixArithTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("two-by-two", new long[][]{new long[]{1, 2}, new long[]{3, 4}}, new long[][]{new long[]{5, 6}, new long[]{7, 8}}, new long[][]{new long[]{19, 22}, new long[]{43, 50}}),
Arguments.of("two-by-three-times-three-by-two", new long[][]{new long[]{1, 2, 3}, new long[]{4, 5, 6}}, new long[][]{new long[]{7, 8}, new long[]{9, 10}, new long[]{11, 12}}, new long[][]{new long[]{58, 64}, new long[]{139, 154}}),
Arguments.of("one-by-one", new long[][]{new long[]{3}}, new long[][]{new long[]{4}}, new long[][]{new long[]{12}}),
Arguments.of("row-times-column", new long[][]{new long[]{1, 2, 3}}, new long[][]{new long[]{4}, new long[]{5}, new long[]{6}}, new long[][]{new long[]{32}}),
Arguments.of("column-times-row", new long[][]{new long[]{1}, new long[]{2}, new long[]{3}}, new long[][]{new long[]{4, 5, 6}}, new long[][]{new long[]{4, 5, 6}, new long[]{8, 10, 12}, new long[]{12, 15, 18}}),
Arguments.of("identity", new long[][]{new long[]{1, 0}, new long[]{0, 1}}, new long[][]{new long[]{5, 6}, new long[]{7, 8}}, new long[][]{new long[]{5, 6}, new long[]{7, 8}}),
Arguments.of("other-order", new long[][]{new long[]{5, 6}, new long[]{7, 8}}, new long[][]{new long[]{1, 2}, new long[]{3, 4}}, new long[][]{new long[]{23, 34}, new long[]{31, 46}}),
Arguments.of("zero-matrix", new long[][]{new long[]{0, 0}, new long[]{0, 0}}, new long[][]{new long[]{1, 2}, new long[]{3, 4}}, new long[][]{new long[]{0, 0}, new long[]{0, 0}}),
Arguments.of("negative-numbers", new long[][]{new long[]{-1, 2}, new long[]{3, -4}}, new long[][]{new long[]{2, 0}, new long[]{1, -1}}, new long[][]{new long[]{0, -2}, new long[]{2, 4}}),
Arguments.of("beyond-32-bit", new long[][]{new long[]{100000, 0}, new long[]{0, 100000}}, new long[][]{new long[]{100000}, new long[]{3}}, new long[][]{new long[]{10000000000L}, new long[]{300000}})
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void multiply(String name, long[][] a, long[][] b, long[][] want) {
assertArrayEquals(want, MatrixArith.multiply(a, b));
}
@Test
void transpose() {
assertArrayEquals(new long[][] {{1, 4}, {2, 5}, {3, 6}}, MatrixArith.transpose(new long[][] {{1, 2, 3}, {4, 5, 6}}));
}
@Test
void sizesMustMatch() {
assertThrows(IllegalArgumentException.class, () -> MatrixArith.multiply(new long[][] {{1, 2}}, new long[][] {{1, 2}}));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
#include "matrix.h"
void transpose(const long long *a, size_t n, size_t m, long long *out) {
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < m; j++) {
out[j * n + i] = a[i * m + j];
}
}
}
// The order i, k, j reads b and out row by row, which suits row-major order.
void matrix_multiply(const long long *a, const long long *b, size_t n, size_t m, size_t p, long long *out) {
for (size_t i = 0; i < n * p; i++) {
out[i] = 0;
}
for (size_t i = 0; i < n; i++) {
for (size_t k = 0; k < m; k++) {
long long x = a[i * m + k];
for (size_t j = 0; j < p; j++) {
out[i * p + j] += x * b[k * p + j];
}
}
}
}
matrix.h 18 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
#ifndef MATRIX_ARITHMETIC_H
#define MATRIX_ARITHMETIC_H
#include <stddef.h>
// The matrices are flat arrays in row-major order: the item in row i and
// column j of an n x m matrix is at index i * m + j.
// Sets out (m x n) to the transpose of a (n x m).
void transpose(const long long *a, size_t n, size_t m, long long *out);
// Sets out (n x p) to the product of a (n x m) and b (m x p).
void matrix_multiply(const long long *a, const long long *b, size_t n, size_t m, size_t p, long long *out);
#endif
test_matrix.c 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
#include "matrix.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test_case {
const char *name;
size_t n, m, p;
long long a[16], b[16], want[16];
};
static const struct test_case cases[] = {
{"two-by-two", 2, 2, 2, {1, 2, 3, 4}, {5, 6, 7, 8}, {19, 22, 43, 50}},
{"two-by-three-times-three-by-two", 2, 3, 2, {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {58, 64, 139, 154}},
{"one-by-one", 1, 1, 1, {3}, {4}, {12}},
{"row-times-column", 1, 3, 1, {1, 2, 3}, {4, 5, 6}, {32}},
{"column-times-row", 3, 1, 3, {1, 2, 3}, {4, 5, 6}, {4, 5, 6, 8, 10, 12, 12, 15, 18}},
{"identity", 2, 2, 2, {1, 0, 0, 1}, {5, 6, 7, 8}, {5, 6, 7, 8}},
{"other-order", 2, 2, 2, {5, 6, 7, 8}, {1, 2, 3, 4}, {23, 34, 31, 46}},
{"zero-matrix", 2, 2, 2, {0, 0, 0, 0}, {1, 2, 3, 4}, {0, 0, 0, 0}},
{"negative-numbers", 2, 2, 2, {-1, 2, 3, -4}, {2, 0, 1, -1}, {0, -2, 2, 4}},
{"beyond-32-bit", 2, 2, 1, {100000, 0, 0, 100000}, {100000, 3}, {10000000000LL, 300000}},
};
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
long long got[16];
matrix_multiply(c->a, c->b, c->n, c->m, c->p, got);
if (memcmp(got, c->want, c->n * c->p * sizeof got[0]) != 0) {
printf("FAIL %s\n", c->name);
failures++;
}
}
const long long m[] = {1, 2, 3, 4, 5, 6}, want[] = {1, 4, 2, 5, 3, 6};
long long t[6];
transpose(m, 2, 3, t);
if (memcmp(t, want, sizeof t) != 0) {
printf("FAIL transpose\n");
failures++;
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
using System;
/// <summary>Matrix arithmetic on jagged arrays of rows.</summary>
public static class MatrixArith
{
/// <summary>Returns the transpose of m: row i of the result is column i of m.</summary>
public static long[][] Transpose(long[][] m)
{
var t = new long[m[0].Length][];
for (int j = 0; j < t.Length; j++)
{
t[j] = new long[m.Length];
for (int i = 0; i < m.Length; i++)
{
t[j][i] = m[i][j];
}
}
return t;
}
/// <summary>Returns the product a times b. The number of columns of a must be the number of rows of b.</summary>
public static long[][] Multiply(long[][] a, long[][] b)
{
if (a[0].Length != b.Length)
{
throw new ArgumentException("the sizes do not match");
}
var c = new long[a.Length][];
for (int i = 0; i < a.Length; i++)
{
c[i] = new long[b[0].Length];
for (int k = 0; k < b.Length; k++)
{
for (int j = 0; j < b[0].Length; j++)
{
c[i][j] += a[i][k] * b[k][j];
}
}
}
return c;
}
}
MatrixArithTests.cs 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
using System;
using Xunit;
public sealed class MatrixArithTests
{
public static TheoryData<string, long[][], long[][], long[][]> Cases => new()
{
{ "two-by-two", new long[][] { new long[] { 1, 2 }, new long[] { 3, 4 } }, new long[][] { new long[] { 5, 6 }, new long[] { 7, 8 } }, new long[][] { new long[] { 19, 22 }, new long[] { 43, 50 } } },
{ "two-by-three-times-three-by-two", new long[][] { new long[] { 1, 2, 3 }, new long[] { 4, 5, 6 } }, new long[][] { new long[] { 7, 8 }, new long[] { 9, 10 }, new long[] { 11, 12 } }, new long[][] { new long[] { 58, 64 }, new long[] { 139, 154 } } },
{ "one-by-one", new long[][] { new long[] { 3 } }, new long[][] { new long[] { 4 } }, new long[][] { new long[] { 12 } } },
{ "row-times-column", new long[][] { new long[] { 1, 2, 3 } }, new long[][] { new long[] { 4 }, new long[] { 5 }, new long[] { 6 } }, new long[][] { new long[] { 32 } } },
{ "column-times-row", new long[][] { new long[] { 1 }, new long[] { 2 }, new long[] { 3 } }, new long[][] { new long[] { 4, 5, 6 } }, new long[][] { new long[] { 4, 5, 6 }, new long[] { 8, 10, 12 }, new long[] { 12, 15, 18 } } },
{ "identity", new long[][] { new long[] { 1, 0 }, new long[] { 0, 1 } }, new long[][] { new long[] { 5, 6 }, new long[] { 7, 8 } }, new long[][] { new long[] { 5, 6 }, new long[] { 7, 8 } } },
{ "other-order", new long[][] { new long[] { 5, 6 }, new long[] { 7, 8 } }, new long[][] { new long[] { 1, 2 }, new long[] { 3, 4 } }, new long[][] { new long[] { 23, 34 }, new long[] { 31, 46 } } },
{ "zero-matrix", new long[][] { new long[] { 0, 0 }, new long[] { 0, 0 } }, new long[][] { new long[] { 1, 2 }, new long[] { 3, 4 } }, new long[][] { new long[] { 0, 0 }, new long[] { 0, 0 } } },
{ "negative-numbers", new long[][] { new long[] { -1, 2 }, new long[] { 3, -4 } }, new long[][] { new long[] { 2, 0 }, new long[] { 1, -1 } }, new long[][] { new long[] { 0, -2 }, new long[] { 2, 4 } } },
{ "beyond-32-bit", new long[][] { new long[] { 100000, 0 }, new long[] { 0, 100000 } }, new long[][] { new long[] { 100000 }, new long[] { 3 } }, new long[][] { new long[] { 10000000000 }, new long[] { 300000 } } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Multiply(string name, long[][] a, long[][] b, long[][] want)
{
Assert.NotNull(name);
Assert.Equal(want, MatrixArith.Multiply(a, b));
}
[Fact]
public void Transpose()
{
long[][] m = [[1, 2, 3], [4, 5, 6]];
long[][] want = [[1, 4], [2, 5], [3, 6]];
Assert.Equal(want, MatrixArith.Transpose(m));
}
[Fact]
public void SizesMustMatch()
{
Assert.Throws<ArgumentException>(() => MatrixArith.Multiply([[1, 2]], [[1, 2]]));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
/** Returns the transpose of m: row i of the result is column i of m. */
export function transpose(m) {
return m[0].map((_, j) => m.map((row) => row[j]));
}
/**
* Returns the product a times b. The number of columns of a must be the
* number of rows of b. Neither matrix changes.
*/
export function matrixMultiply(a, b) {
if (a[0].length !== b.length) {
throw new RangeError(`${a.length}x${a[0].length} times ${b.length}x${b[0].length}: the sizes do not match`);
}
return a.map((row) => b[0].map((_, j) => row.reduce((sum, x, k) => sum + x * b[k][j], 0)));
}
matrix.test.js 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { matrixMultiply, transpose } from "./matrix.js";
const cases = [
["two-by-two", [[1, 2], [3, 4]], [[5, 6], [7, 8]], [[19, 22], [43, 50]]],
["two-by-three-times-three-by-two", [[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 10], [11, 12]], [[58, 64], [139, 154]]],
["one-by-one", [[3]], [[4]], [[12]]],
["row-times-column", [[1, 2, 3]], [[4], [5], [6]], [[32]]],
["column-times-row", [[1], [2], [3]], [[4, 5, 6]], [[4, 5, 6], [8, 10, 12], [12, 15, 18]]],
["identity", [[1, 0], [0, 1]], [[5, 6], [7, 8]], [[5, 6], [7, 8]]],
["other-order", [[5, 6], [7, 8]], [[1, 2], [3, 4]], [[23, 34], [31, 46]]],
["zero-matrix", [[0, 0], [0, 0]], [[1, 2], [3, 4]], [[0, 0], [0, 0]]],
["negative-numbers", [[-1, 2], [3, -4]], [[2, 0], [1, -1]], [[0, -2], [2, 4]]],
["beyond-32-bit", [[100000, 0], [0, 100000]], [[100000], [3]], [[10000000000], [300000]]],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
const before = structuredClone([a, b]);
assert.deepEqual(matrixMultiply(a, b), want);
assert.deepEqual([a, b], before);
});
}
test("transpose", () => {
assert.deepEqual(transpose([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]]);
});
test("sizes-must-match", () => {
assert.throws(() => matrixMultiply([[1, 2]], [[1, 2]]), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
/** A matrix as a list of rows. */
export type Matrix = readonly (readonly number[])[];
/** Returns the transpose of m: row i of the result is column i of m. */
export function transpose(m: Matrix): number[][] {
return m[0]!.map((_, j) => m.map((row) => row[j]!));
}
/**
* Returns the product a times b. The number of columns of a must be the
* number of rows of b. Neither matrix changes.
*/
export function matrixMultiply(a: Matrix, b: Matrix): number[][] {
if (a[0]!.length !== b.length) {
throw new RangeError(`${a.length}x${a[0]!.length} times ${b.length}x${b[0]!.length}: the sizes do not match`);
}
return a.map((row) => b[0]!.map((_, j) => row.reduce((sum, x, k) => sum + x * b[k]![j]!, 0)));
}
matrix.test.ts 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { type Matrix, matrixMultiply, transpose } from "./matrix.ts";
const cases: [string, Matrix, Matrix, number[][]][] = [
["two-by-two", [[1, 2], [3, 4]], [[5, 6], [7, 8]], [[19, 22], [43, 50]]],
["two-by-three-times-three-by-two", [[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 10], [11, 12]], [[58, 64], [139, 154]]],
["one-by-one", [[3]], [[4]], [[12]]],
["row-times-column", [[1, 2, 3]], [[4], [5], [6]], [[32]]],
["column-times-row", [[1], [2], [3]], [[4, 5, 6]], [[4, 5, 6], [8, 10, 12], [12, 15, 18]]],
["identity", [[1, 0], [0, 1]], [[5, 6], [7, 8]], [[5, 6], [7, 8]]],
["other-order", [[5, 6], [7, 8]], [[1, 2], [3, 4]], [[23, 34], [31, 46]]],
["zero-matrix", [[0, 0], [0, 0]], [[1, 2], [3, 4]], [[0, 0], [0, 0]]],
["negative-numbers", [[-1, 2], [3, -4]], [[2, 0], [1, -1]], [[0, -2], [2, 4]]],
["beyond-32-bit", [[100000, 0], [0, 100000]], [[100000], [3]], [[10000000000], [300000]]],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
const before = structuredClone([a, b]);
assert.deepEqual(matrixMultiply(a, b), want);
assert.deepEqual([a, b], before);
});
}
test("transpose", () => {
assert.deepEqual(transpose([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]]);
});
test("sizes-must-match", () => {
assert.throws(() => matrixMultiply([[1, 2]], [[1, 2]]), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
// Package matrix multiplies and transposes matrices stored as slices of rows.
package matrix
import "fmt"
// Transpose returns the transpose of m: row i of the result is column i of m.
func Transpose(m [][]int64) [][]int64 {
t := make([][]int64, len(m[0]))
for j := range t {
t[j] = make([]int64, len(m))
for i := range m {
t[j][i] = m[i][j]
}
}
return t
}
// MatrixMultiply returns the product a times b. The number of columns of a
// must be the number of rows of b.
func MatrixMultiply(a, b [][]int64) ([][]int64, error) {
if len(a[0]) != len(b) {
return nil, fmt.Errorf("%dx%d times %dx%d: the sizes do not match", len(a), len(a[0]), len(b), len(b[0]))
}
c := make([][]int64, len(a))
for i := range a {
c[i] = make([]int64, len(b[0]))
for k, x := range a[i] {
for j, y := range b[k] {
c[i][j] += x * y
}
}
}
return c, nil
}
matrix_test.go 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
package matrix
import (
"reflect"
"testing"
)
var cases = []struct {
name string
a, b, want [][]int64
}{
{"two-by-two", [][]int64{[]int64{1, 2}, []int64{3, 4}}, [][]int64{[]int64{5, 6}, []int64{7, 8}}, [][]int64{[]int64{19, 22}, []int64{43, 50}}},
{"two-by-three-times-three-by-two", [][]int64{[]int64{1, 2, 3}, []int64{4, 5, 6}}, [][]int64{[]int64{7, 8}, []int64{9, 10}, []int64{11, 12}}, [][]int64{[]int64{58, 64}, []int64{139, 154}}},
{"one-by-one", [][]int64{[]int64{3}}, [][]int64{[]int64{4}}, [][]int64{[]int64{12}}},
{"row-times-column", [][]int64{[]int64{1, 2, 3}}, [][]int64{[]int64{4}, []int64{5}, []int64{6}}, [][]int64{[]int64{32}}},
{"column-times-row", [][]int64{[]int64{1}, []int64{2}, []int64{3}}, [][]int64{[]int64{4, 5, 6}}, [][]int64{[]int64{4, 5, 6}, []int64{8, 10, 12}, []int64{12, 15, 18}}},
{"identity", [][]int64{[]int64{1, 0}, []int64{0, 1}}, [][]int64{[]int64{5, 6}, []int64{7, 8}}, [][]int64{[]int64{5, 6}, []int64{7, 8}}},
{"other-order", [][]int64{[]int64{5, 6}, []int64{7, 8}}, [][]int64{[]int64{1, 2}, []int64{3, 4}}, [][]int64{[]int64{23, 34}, []int64{31, 46}}},
{"zero-matrix", [][]int64{[]int64{0, 0}, []int64{0, 0}}, [][]int64{[]int64{1, 2}, []int64{3, 4}}, [][]int64{[]int64{0, 0}, []int64{0, 0}}},
{"negative-numbers", [][]int64{[]int64{-1, 2}, []int64{3, -4}}, [][]int64{[]int64{2, 0}, []int64{1, -1}}, [][]int64{[]int64{0, -2}, []int64{2, 4}}},
{"beyond-32-bit", [][]int64{[]int64{100000, 0}, []int64{0, 100000}}, [][]int64{[]int64{100000}, []int64{3}}, [][]int64{[]int64{10000000000}, []int64{300000}}},
}
func TestMatrixMultiply(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := MatrixMultiply(c.a, c.b)
if err != nil || !reflect.DeepEqual(got, c.want) {
t.Fatalf("got %v, %v, want %v", got, err, c.want)
}
})
}
}
func TestTranspose(t *testing.T) {
got := Transpose([][]int64{{1, 2, 3}, {4, 5, 6}})
if want := [][]int64{{1, 4}, {2, 5}, {3, 6}}; !reflect.DeepEqual(got, want) {
t.Fatalf("got %v", got)
}
}
func TestSizesMustMatch(t *testing.T) {
if _, err := MatrixMultiply([][]int64{{1, 2}}, [][]int64{{1, 2}}); err == nil {
t.Fatal("no error")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
/// Returns the transpose of m: row i of the result is column i of m.
pub fn transpose<R: AsRef<[i64]>>(m: &[R]) -> Vec<Vec<i64>> {
let cols = m[0].as_ref().len();
(0..cols).map(|j| m.iter().map(|row| row.as_ref()[j]).collect()).collect()
}
/// Returns the product a times b, or None if the number of columns of a is
/// not the number of rows of b.
pub fn matrix_multiply<R: AsRef<[i64]>>(a: &[R], b: &[R]) -> Option<Vec<Vec<i64>>> {
if a[0].as_ref().len() != b.len() {
return None;
}
let p = b[0].as_ref().len();
let mut c = vec![vec![0i64; p]; a.len()];
for (i, row) in a.iter().enumerate() {
for (k, &x) in row.as_ref().iter().enumerate() {
for (j, &y) in b[k].as_ref().iter().enumerate() {
c[i][j] += x * y;
}
}
}
Some(c)
}
tests/matrix_test.rs 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-matrix-arithmetic/.
use algo_do_matrix_arithmetic::{matrix_multiply, transpose};
type Case = (&'static str, &'static [&'static [i64]], &'static [&'static [i64]], &'static [&'static [i64]]);
const CASES: &[Case] = &[
("two-by-two", &[&[1, 2], &[3, 4]], &[&[5, 6], &[7, 8]], &[&[19, 22], &[43, 50]]),
("two-by-three-times-three-by-two", &[&[1, 2, 3], &[4, 5, 6]], &[&[7, 8], &[9, 10], &[11, 12]], &[&[58, 64], &[139, 154]]),
("one-by-one", &[&[3]], &[&[4]], &[&[12]]),
("row-times-column", &[&[1, 2, 3]], &[&[4], &[5], &[6]], &[&[32]]),
("column-times-row", &[&[1], &[2], &[3]], &[&[4, 5, 6]], &[&[4, 5, 6], &[8, 10, 12], &[12, 15, 18]]),
("identity", &[&[1, 0], &[0, 1]], &[&[5, 6], &[7, 8]], &[&[5, 6], &[7, 8]]),
("other-order", &[&[5, 6], &[7, 8]], &[&[1, 2], &[3, 4]], &[&[23, 34], &[31, 46]]),
("zero-matrix", &[&[0, 0], &[0, 0]], &[&[1, 2], &[3, 4]], &[&[0, 0], &[0, 0]]),
("negative-numbers", &[&[-1, 2], &[3, -4]], &[&[2, 0], &[1, -1]], &[&[0, -2], &[2, 4]]),
("beyond-32-bit", &[&[100000, 0], &[0, 100000]], &[&[100000], &[3]], &[&[10000000000], &[300000]]),
];
#[test]
fn cases() {
for &(name, a, b, want) in CASES {
let got = matrix_multiply(a, b).expect(name);
assert_eq!(got, want, "{name}");
}
}
#[test]
fn transpose_rows_to_columns() {
let m: &[&[i64]] = &[&[1, 2, 3], &[4, 5, 6]];
assert_eq!(transpose(m), vec![vec![1, 4], vec![2, 5], vec![3, 6]]);
}
#[test]
fn sizes_must_match() {
let a: &[&[i64]] = &[&[1, 2]];
assert_eq!(matrix_multiply(a, a), None);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-matrix-arithmetic/.
# A matrix is a string of rows separated by ";", with the numbers of a row
# separated by spaces: "1 2;3 4" is a 2 x 2 matrix.
# matrix_multiply A B
# Prints the product A times B in the same form. Exits with 1 if the number
# of columns of A is not the number of rows of B.
matrix_multiply() {
local -a ra rb row
local n m p i j k s
IFS=';' read -ra ra <<< "$1"
IFS=';' read -ra rb <<< "$2"
read -ra row <<< "${ra[0]}"; m=${#row[@]}
read -ra row <<< "${rb[0]}"; p=${#row[@]}
n=${#ra[@]}
if (( m != ${#rb[@]} )); then
echo "the sizes do not match" >&2
return 1
fi
# Bash has no two-dimensional arrays, so A and B are flat, in row-major order.
local -a a=() b=() out=()
for (( i = 0; i < n; i++ )); do read -ra row <<< "${ra[i]}"; a+=("${row[@]}"); done
for (( k = 0; k < m; k++ )); do read -ra row <<< "${rb[k]}"; b+=("${row[@]}"); done
for (( i = 0; i < n; i++ )); do
row=()
for (( j = 0; j < p; j++ )); do
s=0
for (( k = 0; k < m; k++ )); do
(( s += a[i * m + k] * b[k * p + j] ))
done
row+=("$s")
done
out+=("${row[*]}")
done
local IFS=';'
echo "${out[*]}"
}
# transpose A
# Prints the transpose of A: row i of the result is column i of A.
transpose() {
local -a ra row out=()
local i j
IFS=';' read -ra ra <<< "$1"
read -ra row <<< "${ra[0]}"
local m=${#row[@]}
for (( j = 0; j < m; j++ )); do
local col=()
for (( i = 0; i < ${#ra[@]}; i++ )); do
read -ra row <<< "${ra[i]}"
col+=("${row[j]}")
done
out+=("${col[*]}")
done
local IFS=';'
echo "${out[*]}"
}
test_matrix.bats 22 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-matrix-arithmetic/.
setup() {
source "$BATS_TEST_DIRNAME/matrix.sh"
}
@test "two-by-two" { run matrix_multiply '1 2;3 4' '5 6;7 8'; [ "$status" -eq 0 ]; [ "$output" = '19 22;43 50' ]; }
@test "two-by-three-times-three-by-two" { run matrix_multiply '1 2 3;4 5 6' '7 8;9 10;11 12'; [ "$status" -eq 0 ]; [ "$output" = '58 64;139 154' ]; }
@test "one-by-one" { run matrix_multiply '3' '4'; [ "$status" -eq 0 ]; [ "$output" = '12' ]; }
@test "row-times-column" { run matrix_multiply '1 2 3' '4;5;6'; [ "$status" -eq 0 ]; [ "$output" = '32' ]; }
@test "column-times-row" { run matrix_multiply '1;2;3' '4 5 6'; [ "$status" -eq 0 ]; [ "$output" = '4 5 6;8 10 12;12 15 18' ]; }
@test "identity" { run matrix_multiply '1 0;0 1' '5 6;7 8'; [ "$status" -eq 0 ]; [ "$output" = '5 6;7 8' ]; }
@test "other-order" { run matrix_multiply '5 6;7 8' '1 2;3 4'; [ "$status" -eq 0 ]; [ "$output" = '23 34;31 46' ]; }
@test "zero-matrix" { run matrix_multiply '0 0;0 0' '1 2;3 4'; [ "$status" -eq 0 ]; [ "$output" = '0 0;0 0' ]; }
@test "negative-numbers" { run matrix_multiply '-1 2;3 -4' '2 0;1 -1'; [ "$status" -eq 0 ]; [ "$output" = '0 -2;2 4' ]; }
@test "beyond-32-bit" { run matrix_multiply '100000 0;0 100000' '100000;3'; [ "$status" -eq 0 ]; [ "$output" = '10000000000;300000' ]; }
@test "transpose" { run transpose '1 2 3;4 5 6'; [ "$output" = '1 4;2 5;3 6' ]; }
@test "sizes-must-match" { run matrix_multiply '1 2' '1 2'; [ "$status" -eq 1 ]; }
References
- Rosetta Code, Matrix multiplication (task text, from acmeism/RosettaCodeData), task text
- Rosetta Code, Matrix transposition (task text, from acmeism/RosettaCodeData), task text
- Wikipedia, Matrix multiplication, Introduction; Fundamental properties; Computational complexity
- The Python Standard Library, Built-in Functions, zip
- PEP 465, A dedicated infix operator for matrix multiplication, Abstract; Specification
- Wikipedia, Row- and column-major order, Introduction; Programming languages and libraries
- Python Programming FAQ, How do I create a multidimensional list?
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag R3P151 Edit this page History Report an error Markdown