matrices.Matrix

class matrices.Matrix[source]

Bases: MatrixABC[~T]

Mutable 2-dimensional Matrix type.

Matrix objects can be instantiated in several different ways:

Matrix(data: MatrixT[T] [, shape: tuple[int, int], *, default: T]) Matrix[T]

Initialises a new Matrix from another MatrixT instance (i.e. another Matrix or FrozenMatrix).

The shape and default arguments are optional – if omitted the values from the MatrixT passed as data will be used.

Example:
>>> m = Matrix([1, 2, 3, 4], shape=(2, 2), default=0)
>>> print(m)
    0  1
  ┌      ┐
0 │ 1  2 │
1 │ 3  4 │
  └      ┘
>>> n = Matrix(m, shape=(3, 3))  # default is inferred from m
>>> print(n)
    0  1  2
  ┌         ┐
0 │ 1  2  0 │
1 │ 3  4  0 │
2 │ 0  0  0 │
  └         ┘
Matrix(data: Sequence[Sequence[T]] [, shape: tuple[int, int]], *, default: T) Matrix[T]

Initialises a new Matrix from a sequence of sequences (e.g. a list of lists, or a tuple of tuples).

The shape argument is optional. If provided data will be reshaped to conform to the specified shape, otherwise the shape will be inferred as follows: The row count equals the length of the outer sequence, the column count equals the length of the first subsequence.

The default argument is required.

Example:
>>> m = Matrix([[1, 2, 3], [4, 5, 6]], default=0)
>>> print(m)
    0  1  2
  ┌         ┐
0 │ 1  2  3 │
1 │ 4  5  6 │
  └         ┘
>>> m = Matrix(((1, 2), ), shape=(2, 2), default=0)
>>> print(m)
    0  1
  ┌      ┐
0 │ 1  2 │
1 │ 0  0 │
  └      ┘
Matrix(data: Sequence[T], shape: tuple[int, int], *, default: T) Matrix[T]

Initialises a new Matrix from a “flat” sequence.

The shape and default arguments are both required, because neither of them can be inferred from data.

The values from data will be read row-wise, and padded with default if they run out before the entire Matrix is filled. Leftover values in data will simply be disregarded.

Example:
>>> m = Matrix([1, 2, 3, 4, 5], shape=(2, 3), default=0)
>>> print(m)
    0  1  2
  ┌         ┐
0 │ 1  2  3 │
1 │ 4  5  0 │
  └         ┘
>>> m = Matrix(range(1, 100), shape=(2, 5), default=0)
>>> print(m)
    0  1  2  3   4
  ┌                ┐
0 │ 1  2  3  4   5 │
1 │ 6  7  8  9  10 │
  └                ┘
__init__(*args, **kwargs)

Initialise a new Matrix/FrozenMatrix instance.

Parameters:
  • data (MatrixABC[T] | Sequence[T] | Sequence[Sequence[T]]) – The initial data for the matrix. This can be another MatrixT instance, a sequence of values, or a sequence of a sequence of values. This argument is required, but you can simply pass an empty sequence (e.g. []) to have the matrix filled with default instead.

  • shape (tuple[int, int]) – The shape the matrix should have, as a tuple specifying (rows, cols). This argument is required if data is a flat sequence. If data is a sequence of sequences or another MatrixT, then shape will be inferred if it is not provided, or data will be reshaped to shape if it is provided and doesn’t presently conform to shape.

  • default (T) – A keyword-only argument specifying the default value for matrix cells. This will be used to fill in the value for cells which do not have one assigned, are deleted, newly inserted, etc. It is also used as in evaluating the truthiness of a MatrixT (a MatrixT is True if at least one of its cells’ values is not equal to default). The default argument is required unless data is of type MatrixT, in which case it will be inferred if not explicity specified.

  • args (Any)

  • kwargs (Any)

Methods

__init__(*args, **kwargs)

Initialise a new Matrix/FrozenMatrix instance.

appendcol(data)

Appends a column with values data to the right of the matrix.

appendrow(data)

Appends a row with values data at the bottom of the matrix.

asdict()

Returns the matrix data as a dictionary with coordinates as key.

aslist(*[, by])

Returns the matrix data as a list of lists.

copy()

Returns a copy of the matrix object.

empty()

Returns False if at least one value in the

flip(*[, by])

Flips a matrix vertically or horizontally.

fliph()

Flips a matrix horizontally (by columns).

flipv()

Flips a matrix vertically (by rows).

foreach(func, *args, **kwargs)

Applies func to each cell in the matrix.

get(row_or_key[, col])

Return an item or submatrix based on row and colum indices.

imatadd(other)

Add the matrix other in-situ.

imatmul(other)

Multiply with the matrix other in-situ.

imatsub(other)

Substitute the matrix other in-situ.

insertcol(index, data)

Inserts a column with values data before index.

insertrow(index, data)

Inserts a row with values data before index.

iscaladd(scalar)

rtype:

Union[Self, Matrix[~V]]

iscalmul(scalar)

rtype:

Union[Self, Matrix[~V]]

iscalsub(scalar)

rtype:

Union[Self, Matrix[~V]]

items(*[, by])

Returns a list of key--value pairs for all cells in the matrix.

keys(*[, by])

Returns a list of keys for all cells in the matrix.

map(func, *args, **kwargs)

Applies func to each cell in the matrix and stores the return value of func as the new cell value.

matadd(other)

Adds two matrices.

matmul(other)

Multiplies two matrices.

matsub(other)

Subtracts two matrices.

prependcol(data)

Prepends a column with values data to the right of the matrix.

prependrow(data)

Prepends a row with values data at the bottom of the matrix.

removecol(index)

Remove the column at index.

removerow(index)

Removes the row at index.

resize(rows[, cols])

Grows or shrinks a matrix.

scaladd(scalar)

Adds scalar to the value of each cell in the matrix.

scalmul(scalar)

Multiplies the value of each cell in the matrix with scalar.

scalsub(scalar)

Subtracts scalar from the value of each cell in the matrix.

set(arg1[, arg2, arg3])

(TO BE WRITTEN)

submatrix(rows, cols)

Return a submatrix bounded by rows and cells.

swapcols(a_index, b_index)

Swaps the two columns at indices a_index and b_index.

swaprows(a_index, b_index)

Swaps the two rows at indices a_index and b_index.

transpose()

Transposes the rows and columns of the matrix.

values(*[, by])

Returns a flat list of the matrix's values.

Attributes

default

Returns the default value for the matrix.

shape

Returns the shape of the matrix.

__init__(*args, **kwargs)

Initialise a new Matrix/FrozenMatrix instance.

Parameters:
  • data (MatrixABC[T] | Sequence[T] | Sequence[Sequence[T]]) – The initial data for the matrix. This can be another MatrixT instance, a sequence of values, or a sequence of a sequence of values. This argument is required, but you can simply pass an empty sequence (e.g. []) to have the matrix filled with default instead.

  • shape (tuple[int, int]) – The shape the matrix should have, as a tuple specifying (rows, cols). This argument is required if data is a flat sequence. If data is a sequence of sequences or another MatrixT, then shape will be inferred if it is not provided, or data will be reshaped to shape if it is provided and doesn’t presently conform to shape.

  • default (T) – A keyword-only argument specifying the default value for matrix cells. This will be used to fill in the value for cells which do not have one assigned, are deleted, newly inserted, etc. It is also used as in evaluating the truthiness of a MatrixT (a MatrixT is True if at least one of its cells’ values is not equal to default). The default argument is required unless data is of type MatrixT, in which case it will be inferred if not explicity specified.

  • args (Any)

  • kwargs (Any)

appendcol(data)

Appends a column with values data to the right of the matrix.

This is equivalent to m.insertcol(len(m), data).

data must be a sequence with length at least matching the number of rows in the matrix. Unused values will be ignored.

Modifies the matrix in-situ and returns self if the matrix is mutable, otherwise returns an expanded copy of the matrix.

Parameters:

data (Sequence[~T]) – The data to be inserted into the new column.

Return type:

Self

Returns:

its own Matrix instance if mutable, a copy of the FrozenMatrix instance if immutable.

appendrow(data)

Appends a row with values data at the bottom of the matrix.

This is equivalent to m.insertrow(len(m), data).

data must be a sequence with length at least matching the number of columns in the matrix. Unused values will be ignored.

Modifies the matrix in-situ and returns self if the matrix is mutable, otherwise returns an expanded copy of the matrix.

Parameters:

data (Sequence[~T]) – The data to be inserted into the new row.

Return type:

Self

Returns:

its own Matrix instance if mutable, a copy of the FrozenMatrix instance if immutable.

asdict()

Returns the matrix data as a dictionary with coordinates as key.

The returned dictionary’s keys are tuples of the form (row, column).

For example, the matrix:

     0  1  2
   ┌         ┐
0  │ 1  2  3 │
1  │ 4  5  6 │
   └         ┘

will be returned as a dict of the form:

{
    (0, 0): 1,
    (0, 1): 2,
    (0, 2): 3,
    (1, 0): 4,
    (1, 1): 5,
    (1, 2): 6
}
Return type:

dict[tuple[int, int], ~T]

Returns:

A dictionary with coordinates as keys and cell values as values.

aslist(*, by='row')

Returns the matrix data as a list of lists.

If by is "row" (the default), then the returned list of lists is in the format rows[columns]. If by is "col" then the returned list is in the format columns[rows].

For example, the matrix:

     0  1  2
   ┌         ┐
0  │ 1  2  3 │
1  │ 4  5  6 │
   └         ┘

will be returned as a list of the form:

[
    [1, 2, 3],
    [4, 5, 6]
]

Note that this is different from invoking list(m) on a matrix, which does not return a list of list with the matrix’s values, but rather a list of (row, col) index pairs for each cell, equivalent to calling keys() on a matrix object.

Parameters:

by (Union[Literal['row'], Literal['col']]) – Specifies whether to build the list row-wise or column-wise.

Return type:

list[list[~T]]

Returns:

A list containing one list for each row/column, depending on the direction indicated by the by argument.

copy()

Returns a copy of the matrix object.

Return type:

Self

Returns:

A copy of self.

empty()

Returns False if at least one value in the

Return type:

bool

flip(*, by='row')[source]

Flips a matrix vertically or horizontally.

Effectively reverses the order of the matrix’s rows or columns.

Whether the flipping is applied to the rows or columns is specified by the keyword-only argument by. The default is "row", which flips the matrix vertically.

m.flip() and m.flip(by="row") are equivalent to m.flipv().

m.flip(by="column") is equivalent to m.fliph().

Parameters:

by (Union[Literal['row'], Literal['col']]) – Whether to flop row-wise or column-wise, must be one of the literal strings "row" (the default) or "col".

Return type:

Self

Returns:

its own Matrix instance if mutable, a copy of the FrozenMatrix instance if immutable.

fliph()

Flips a matrix horizontally (by columns).

This effectively reverses the order of the columns of the matrix.

This has the effect of turning a matrix such as:

    0  1  2
  ┌         ┐
0 │ 1  2  3 │
1 │ 4  5  6 │
  └         ┘

into the matrix:

    0  1  2
  ┌         ┐
0 │ 3  2  1 │
1 │ 6  5  4 │
  └         ┘

Modifies the matrix in-situ if the matrix is mutable, otherwise returns a copy of the matrix with the order of columns reversed.

Return type:

Self

Returns:

its own Matrix instance if mutable, a copy of the FrozenMatrix instance if immutable.

flipv()

Flips a matrix vertically (by rows).

This effectively reverses the order of the rows of the matrix.

This has the effect of turning a matrix such as:

    0  1  2
  ┌         ┐
0 │ 1  2  3 │
1 │ 4  5  6 │
2 │ 7  8  9 │
  └         ┘

into the matrix:

    0  1  2
  ┌         ┐
0 │ 7  8  9 │
1 │ 4  5  6 │
2 │ 1  2  3 │
  └         ┘

Modifies the matrix in-situ if the matrix is mutable, otherwise returns a copy of the matrix with the order of rows reversed.

Return type:

Self

Returns:

its own Matrix instance if mutable, a copy of the FrozenMatrix instance if immutable.

foreach(func, *args, **kwargs)

Applies func to each cell in the matrix.

Any additional args or kwargs passed after func will be passed as arguments to func.

The return value of func will be ignored. To mutate the values of each cell in-situ based on the return value, use map() instead.

Example:
>>> print(m)
┌         ┐
│ 1  2  3 │
│ 4  5  6 │
└         ┘
>>> m.foreach(lambda a: print(a**2, end=", "))
1, 4, 9, 16, 25, 36,
Parameters:
  • func (Callable[…, ~V]) – A callable accepting at least one argument (namely the value of each cell as the matrix is being iterated over).

  • args (Any)

  • kwargs (Any)

Return type:

Union[Self, MatrixABC[~V]]

Returns:

its own Matrix instance or a copy of the FrozenMatrix instance.

get(row_or_key, col=None)

Return an item or submatrix based on row and colum indices.

Can be invoked as either get((row, col)) or get(row, col).

Returns the value of a cell if both rows and cols are integers which together reference a unique cell. Returns a submatrix if either rows, cols or both are slice objects or tuples of integers with several row/column indices.

Parameters:
  • row_or_key (Union[slice, int, tuple[int, …], tuple[Union[slice, int, tuple[int, …]], Union[slice, int, tuple[int, …]]]]) – The row index or row indices (as a tuple or slice) of the row(s) to be returned, or a tuple with (row, col) argument values if col is omitted.

  • col (Union[slice, int, tuple[int, …], None]) – The column index or column indices (as a tuple or slice) of the column(s) to be returned.

Return type:

Union[~T, Self]

Returns:

The value of the matrix cell if both row and col are integers refering to a single cell, otherwise a submatrix covering the are selected by row and col.

imatadd(other)[source]

Add the matrix other in-situ.

This behaves similar to matadd(), but applies the result to the Matrix instance itself.

Equivalent to using the += operator with another MatrixT as the right operand.

Example:
>>> m = Matrix([[1, 1, 1], [2, 2, 2]], default=0)
>>> m.imatadd(m)
>>> print(m)
    0  1  2
  ┌         ┐
0 │ 2  2  2 │
1 │ 4  4  4 │
  └         ┘
Parameters:

other (MatrixABC[~V]) – The MatrixT instance whose cell values should be added to the cell values of this matrix.

Return type:

Union[Self, Matrix[~V]]

Returns:

Its own Matrix instance.

imatmul(other)[source]

Multiply with the matrix other in-situ.

This behaves similar to matmul(), but applies the result to the Matrix instance itself.

Note that this will alter the shape of the matrix.

The matrix passed as other must have the inverse shape of the present matrix. E.g. if the instance has shape (2, 3), then the other matrix must have the shape (3, 2), otherwise the dot product is undefined and a ValueError will be raised.

Equivalent to using the @= operator with another MatrixT as the right operand.

Example:
>>> m = Matrix([[1, 1, 1], [2, 2, 2]], default=0)
>>> n = Matrix([[1, 2], [1, 2], [1, 2]], default=0)
>>> m.imatmul(m)
>>> print(m)
    0   1
  ┌       ┐
0 │ 3   6 │
1 │ 6  12 │
  └       ┘
Parameters:

other (MatrixABC[~V]) – The MatrixT instance whose cell values should be added to the cell values of this matrix.

Return type:

Union[Self, Matrix[~V]]

Returns:

Its own Matrix instance.

Raises:

ValueError – if the shape of other is not the inverse of this matrix instance itself.

imatsub(other)[source]

Substitute the matrix other in-situ.

This behaves similar to matsub(), but applies the result to the Matrix instance itself.

Equivalent to using the -= operator with another MatrixT as the right operand.

Example:
>>> m = Matrix([[1, 1, 1], [2, 2, 2]], default=0)
>>> m.imatsub(m)
>>> print(m)
    0  1  2
  ┌         ┐
0 │ 0  0  0 │
1 │ 0  0  0 │
  └         ┘
Parameters:

other (MatrixABC[~V]) – The MatrixT instance whose cell values should be subtracted from the cell values of this matrix.

Return type:

Union[Self, Matrix[~V]]

Returns:

Its own Matrix instance.

insertcol(index, data)[source]

Inserts a column with values data before index.

data must be a sequence with length at least matching the number of rows in the matrix. Unused values will be ignored.

Modifies the matrix in-situ if the matrix is mutable, otherwise returns an expanded copy of the matrix.

Parameters:
  • index (int) – The colmn index before which the new column should be inserted.

  • data (Sequence[~T]) – The data to be inserted into the new column.

Return type:

Self

Returns:

its own Matrix instance or a copy of the FrozenMatrix instance.

insertrow(index, data)[source]

Inserts a row with values data before index.

data must be a sequence with length at least matching the number of columns in the matrix. Unused values will be ignored.

Modifies the matrix in-situ if the matrix is mutable, otherwise returns an expanded copy of the matrix.

Parameters:
  • index (int) – The row index before which the new row should be inserted.

  • data (Sequence[~T]) – The data to be inserted into the new row.

Return type:

Self

Returns:

its own Matrix instance or a copy of the FrozenMatrix instance.

iscaladd(scalar)[source]
Return type:

Union[Self, Matrix[~V]]

Parameters:

scalar (V)

iscalmul(scalar)[source]
Return type:

Union[Self, Matrix[~V]]

Parameters:

scalar (V)

iscalsub(scalar)[source]
Return type:

Union[Self, Matrix[~V]]

Parameters:

scalar (V)

items(*, by='row')

Returns a list of key–value pairs for all cells in the matrix.

Each item in the returned list is a tuple of the form ((row, col), value).

This is useful for iteration over a matrix where the row and column indices should be kept track of. For example, if the row and column index don’t need to be unpacked

>>> m = Matrix([[1, 2], [3, 4]], default=0)
>>> for key, value in m.items():
...     print(f"{key}: {value}")
...
(0, 0): 1
(0, 1): 2
(1, 0): 3
(1, 1): 4

If the row and key values should be unpacked this can be achieved by further tuple unpacking

>>> for (row, col), val in m.items():
...     print(f"{row}, {col}: {val}")
...
0, 0: 1
0, 1: 2
1, 0: 3
1, 1: 4
Parameters:

by (Union[Literal['row'], Literal['col']]) – The direction in which the matrix values should be serialised into a flat sequence, row-wise or column-wise.

Return type:

list[tuple[tuple[int, int], ~T]]

Returns:

A list with pairs of the matrix’s keys and corresponding values.

keys(*, by='row')

Returns a list of keys for all cells in the matrix.

The list contains tuples with the coordinates in the form (row, col). These are sorted by row first if by is set to "row" (the default), and they are sorted by column first if by is set to "col".

Parameters:

by (Union[Literal['row'], Literal['col']]) – Whether to sort the keys row-wise or column-wise.

Return type:

list[tuple[int, int]]

Returns:

A list of tuples with coordinates for each cell, sorted as indicated by the by argument.

map(func, *args, **kwargs)[source]

Applies func to each cell in the matrix and stores the return value of func as the new cell value.

Any additional args or kwargs passed after func will be passed as parameters to func.

This will mutate the values of each cell in-situ based on the return value of func. To apply func without affecting the values store in the matrix, use foreach() instead.

Returns the original matrix with func applied in-situ if the matrix is mutable, otherwise returns a copy of the matrix with func applied.

Example:
>>> m = Matrix([[1, 2, 3], [4, 5, 6]], default=0)
>>> print(m)
    0  1  2
  ┌         ┐
0 │ 1  2  3 │
1 │ 4  5  6 │
  └         ┘
>>> print(m.map(lambda a: a**2))
     0   1   2
  ┌            ┐
0 │  1   4   9 │
1 │ 16  25  36 │
  └            ┘
Parameters:
  • func (Callable[…, ~V]) – A callable accepting at least one argument (namely the value of each cell as the matrix is being iterated over).

  • args (Any) – Additional positional arguments to be passed to func.

  • kwargs (Any) – Additional keyword arguments to be passed to func.

Return type:

Union[Self, Matrix[~V]]

Returns:

its own Matrix instance if mutable, a copy of the FrozenMatrix instance if immutable.

matadd(other)

Adds two matrices.

The other matrix must have the same shape as the matrix to which it is added.

Returns a new matrix of the same shape as the original matrix.

Parameters:

other (MatrixABC[~V]) – The Matrix or FrozenMatrix to be added to this one.

Return type:

Union[Self, MatrixABC[~V]]

Returns:

a copy of the Matrix or FrozenMatrix instance with other added.

matmul(other)

Multiplies two matrices.

The other matrix’s shape must be the inverse of the matrix to which it applies. For example, if we have a matrix of shape (2, 3), it can only be multiplied with a matrix of the shape (3, 2).

Returns a new matrix of shape (k, n), where k is the number of rows of the original matrix and n is the number of columns of the other matrix.

Parameters:

other (MatrixABC[~V]) – The Matrix or FrozenMatrix to be multiplied with this one.

Return type:

Union[Self, MatrixABC[~V]]

Returns:

a copy of the Matrix or FrozenMatrix instance with other multiplied into it.

matsub(other)

Subtracts two matrices.

The other matrix must have the same shape as the matrix from which it is subtracted.

Returns a new matrix of the same shape as the original matrix.

Parameters:

other (MatrixABC[~V]) – The Matrix or FrozenMatrix to be subtracted from this one.

Return type:

Union[Self, MatrixABC[~V]]

Returns:

a copy of the Matrix or FrozenMatrix instance with other subtracted.

prependcol(data)

Prepends a column with values data to the right of the matrix.

This is equivalent to m.insertcol(0, data).

data must be a sequence with length at least matching the number of columns in the matrix. Unused values will be ignored.

Modifies the matrix in-situ if the matrix is mutable, otherwise returns an expanded copy of the matrix.

Parameters:

data (Sequence[~T]) – The data to be inserted into the new column.

Return type:

Self

Returns:

its own Matrix instance or a copy of the FrozenMatrix instance.

prependrow(data)

Prepends a row with values data at the bottom of the matrix.

This is equivalent to m.insertrow(0, data).

data must be a sequence with length at least matching the number of rows in the matrix. Unused values will be ignored.

Modifies the matrix in-situ if the matrix is mutable, otherwise returns an expanded copy of the matrix.

Parameters:

data (Sequence[~T]) – The data to be inserted into the new row.

Return type:

Self

Returns:

its own Matrix instance or a copy of the FrozenMatrix instance.

removecol(index)[source]

Remove the column at index.

Caution

The column is removed completely from the matrix, and the matrix’s shape will be altered. Calling this function does not merely reset the values of items in the targeted column to their default!

Parameters:

index (int) – The index of the column to be removed.

Return type:

Self

Returns:

its own Matrix instance if mutable, a copy of the FrozenMatrix instance if immutable.

removerow(index)[source]

Removes the row at index.

Caution

The row is removed completely from the matrix, and the matrix’s shape will be altered. Calling this function does not merely reset the values of items in the targeted row to their default!

Parameters:

index (int) – The index of the row to be removed.

Return type:

Self

Returns:

its own Matrix instance if mutable, a copy of the FrozenMatrix instance if immutable.

resize(rows, cols=None)[source]

Grows or shrinks a matrix.

Grows or shrinks a matrix depending on whether the new shape supplied is greater or smaller in any dimension; does nothing if the new shape is identical to the original shape.

Where the new shape adds new rows or columns, the new cells are populated by the matrix’s default value.

Where the new shape removes rows or columns, the values of the removed cells will be lost.

Modifies the matrix in-situ if it is mutable, otherwise returns a resized copy of the matrix.

Can be called either with the positional-only argument shape as

resize(shape: tuple[int, int]) Self[source]
Parameters:
  • rows (int | tuple[int, int])

  • cols (int | None)

Return type:

Self

or with two integer arguments for rows and cols as

resize(rows: int, cols: int) Self[source]
Parameters:
  • rows (int | tuple[int, int])

  • cols (int | None)

Return type:

Self

Parameters:
  • shape (tuple[int, int]) – A tuple with the sizes for (rows, columns) that the resized matrix should have.

  • rows (Union[int, tuple[int, int]]) – The number of rows the resized matrix should have.

  • cols (Optional[int]) – The number of columns the resized matrix should have.

Return type:

Self

Returns:

its own Matrix instance or a copy of the FrozenMatrix instance.

scaladd(scalar)

Adds scalar to the value of each cell in the matrix.

Returns a copy of the matrix with the scalar addition applied.

Parameters:

scalar (~V) – The scalar to be added to each cell’s value.

Return type:

Union[Self, MatrixABC[~V]]

Returns:

a copy of the Matrix or FrozenMatrix instance with scalar added to its cell values.

scalmul(scalar)

Multiplies the value of each cell in the matrix with scalar.

Returns a copy of the matrix with the scalar multiplication applied.

Parameters:

scalar (~V) – The scalar to be subtracted from each cell’s value.

Return type:

Union[Self, MatrixABC[~V]]

Returns:

a copy of the Matrix or FrozenMatrix instance with scalar multiplied into each cell’s values.

scalsub(scalar)

Subtracts scalar from the value of each cell in the matrix.

Returns a copy of the matrix with the scalar subtraction applied.

Parameters:

scalar (~V) – The scalar to be subtracted from each cell’s value.

Return type:

Union[Self, MatrixABC[~V]]

Returns:

a copy of the Matrix or FrozenMatrix instance with scalar subtracted from its cell values.

set(arg1, arg2=NotGiven, arg3=NotGiven, /)[source]

(TO BE WRITTEN)

Return type:

Self

Parameters:
  • arg1 (IndexT | tuple[IndexT, IndexT])

  • arg2 (IndexT | T | Sequence[T] | Sequence[Sequence[T] | MatrixABC[T]] | Sentinel)

  • arg3 (T | Sequence[T] | Sequence[Sequence[T] | MatrixABC[T]] | Sentinel)

submatrix(rows, cols)

Return a submatrix bounded by rows and cells.

Return type:

Self

Parameters:
  • rows (matrices._types.IndexT)

  • cols (matrices._types.IndexT)

swapcols(a_index, b_index)[source]

Swaps the two columns at indices a_index and b_index.

Modifies the matrix in-situ if the matrix is mutable, otherwise returns a copy with the two columns swapped.

Parameters:
  • a_index (int) – The index of the first column to be swapped.

  • b_index (int) – The index of the second column, which a_index should be swapped with.

Return type:

Self

Returns:

its own Matrix instance or a copy of the FrozenMatrix instance.

swaprows(a_index, b_index)[source]

Swaps the two rows at indices a_index and b_index.

Modifies the matrix in-situ if the matrix is mutable, otherwise returns a copy with the two rows swapped.

Parameters:
  • a_index (int) – The index of the first row to be swapped.

  • b_index (int) – The index of the second row, which a_index should be swapped with.

Return type:

Self

Returns:

its own Matrix instance or a copy of the FrozenMatrix instance.

transpose()[source]

Transposes the rows and columns of the matrix.

This has the effect of turning a matrix such as:

    0  1  2
  ┌         ┐
0 │ 1  2  3 │
1 │ 4  5  6 │
  └         ┘

into the matrix:

    0  1
  ┌      ┐
0 │ 1  4 │
1 │ 2  5 │
2 │ 3  6 │
  └      ┘

Modifies the matrix in-situ if it is mutable, otherwise returns a transposed copy of the matrix.

Return type:

Self

Returns:

its own Matrix instance if mutable, a copy of the FrozenMatrix instance if immutable.

values(*, by='row')

Returns a flat list of the matrix’s values.

By default, the returned list will be sequenced row by row. For example, the matrix:

    0  1  2
  ┌         ┐
0 │ 1  2  3 │
1 │ 4  5  6 │
  └         ┘

will be returned as the list:

[1, 2, 3, 4, 5, 6]

This behaviour can be modified by passing the literal "column" as the keyword-only argument by, such that m.values(by="column") would return:

[1, 4, 2, 5, 3, 6]
Parameters:

by (Union[Literal['row'], Literal['col']]) – The direction in which the matrix values should be serialised into a flat sequence, row-wise or column-wise.

Return type:

list[~T]

Returns:

A list with the matrix’s values.

property default: T

Returns the default value for the matrix.

Return type:

~T

property shape: tuple[int, int]

Returns the shape of the matrix.

Return type:

tuple[int, int]