Matrix

public struct Matrix
extension Matrix: ExpressibleByArrayLiteral
extension Matrix: CustomStringConvertible
extension Matrix: Sequence

Simple Matrix type

Warning

Not available on Linux

Matrix uses the Accelerate.framework for most of its operations, so it should be pretty fast – but no doubt there’s lots of room for improvement. Since the Accelerate framework works a lot with Double, I had to find a compromise between performance and compatibility with other Euler object, such as BigNumber. I made some convenience initializer, but make sure your code converts these BigNumber to Double using BigNumber.asDouble

For example, here’s how you can use Matrix as part of the k-nearest neighbors algorithm:

// load your data set into matrix X, where each row represents one training
// example, and each column a feature
let X = Matrix(rows: 10000, columns: 200)

// load your test example into the row vector x
let x = Matrix(rows: 1, columns: 200)

// Calculate the distance between the test example and every training example
// and store this in a new column vector
let distances = (x.tile(X.rows) - X).pow(2).sumRows().sqrt()

Operations

  • Inverse of the Matrix

    In linear algebra, an n-by-n square matrix A is called invertible (also nonsingular or nondegenerate) if there exists an n-by-n square matrix B such that AB = BA = I_n where In denotes the n-by-n identity matrix and the multiplication used is ordinary matrix multiplication.

    Declaration

    Swift

    public func inverse() -> Matrix
  • Transpose the Matrix by flipping it diagonally

    In linear algebra, the transpose of a matrix is an operator which flips a matrix over its diagonal, that is it switches the row and column indices of the matrix by producing another matrix denoted as A’

    Declaration

    Swift

    public func transpose() -> Matrix

Operators

  • Transpose the Matrix by flipping it diagonally

    Declaration

    Swift

    postfix static func  (value: Matrix) -> Matrix

    Parameters

    value

    The Matrix you want to transpose

Arithmetic

  • Element-by-element addition. Either:

    • both matrices have the same size
    • rhs is a row vector with an equal number of columns as lhs
    • rhs is a column vector with an equal number of rows as lhs

    Declaration

    Swift

    static func + (lhs: Matrix, rhs: Matrix) -> Matrix
  • Element-by-element addition of the same Matrix with another

    Declaration

    Swift

    static func += (lhs: inout Matrix, rhs: Matrix)
  • Adds a scalar to each element of the matrix.

    Declaration

    Swift

    static func + (lhs: Matrix, rhs: Double) -> Matrix
  • Adds a scalar to each element of the same matrix.

    Declaration

    Swift

    static func += (lhs: inout Matrix, rhs: Double)
  • Adds a scalar to each element of the matrix.

    Declaration

    Swift

    static func + (lhs: Double, rhs: Matrix) -> Matrix
  • Element-by-element subtraction. Either:

    • both matrices have the same size
    • rhs is a row vector with an equal number of columns as lhs
    • rhs is a column vector with an equal number of rows as lhs

    Declaration

    Swift

    static func - (lhs: Matrix, rhs: Matrix) -> Matrix
  • Subtracts a scalar from each element of the matrix.

    Declaration

    Swift

    static func - (lhs: Matrix, rhs: Double) -> Matrix
  • Subtracts a scalar from each element of the same matrix.

    Declaration

    Swift

    static func -= (lhs: inout Matrix, rhs: Double)
  • Subtracts each element of the matrix from a scalar.

    Declaration

    Swift

    static func - (lhs: Double, rhs: Matrix) -> Matrix
  • Negates each element of the matrix.

    Declaration

    Swift

    prefix static func - (m: Matrix) -> Matrix
  • Multiplies two matrices, or a matrix with a vector.

    Declaration

    Swift

    static func <*> (lhs: Matrix, rhs: Matrix) -> Matrix
  • Warning: This is not the dot product, see <*> for that.

    Multiplies each element of the lhs matrix by each element of the rhs matrix. Either:

    • both matrices have the same size
    • rhs is a row vector with an equal number of columns as lhs
    • rhs is a column vector with an equal number of rows as lhs

    Declaration

    Swift

    static func * (lhs: Matrix, rhs: Matrix) -> Matrix
  • Multiplies each element of the matrix with a scalar.

    Declaration

    Swift

    static func * (lhs: Matrix, rhs: Double) -> Matrix
  • Multiplies each element of the matrix with a scalar.

    Declaration

    Swift

    static func * (lhs: Double, rhs: Matrix) -> Matrix
  • Divides a matrix by another. This is the same as multiplying with the inverse.

    Declaration

    Swift

    static func </> (lhs: Matrix, rhs: Matrix) -> Matrix
  • Divides each element of the lhs matrix by each element of the rhs matrix. Either:

    • both matrices have the same size
    • rhs is a row vector with an equal number of columns as lhs
    • rhs is a column vector with an equal number of rows as lhs

    Declaration

    Swift

    static func / (lhs: Matrix, rhs: Matrix) -> Matrix
  • Divides each element of the matrix by a scalar.

    Declaration

    Swift

    static func / (lhs: Matrix, rhs: Double) -> Matrix
  • Divides a scalar by each element of the matrix.

    Declaration

    Swift

    static func / (lhs: Double, rhs: Matrix) -> Matrix

Other maths

  • Exponentiates each element of the matrix.

    Declaration

    Swift

    public func exp() -> Matrix
  • Takes the natural logarithm of each element of the matrix.

    Declaration

    Swift

    public func log() -> Matrix
  • Raised each element of the matrix to power alpha.

    Declaration

    Swift

    public func pow(_ alpha: Double) -> Matrix
  • Takes the square root of each element of the matrix.

    Declaration

    Swift

    public func sqrt() -> Matrix
  • Adds up all the elements in the matrix.

    Declaration

    Swift

    public func sum() -> BigDouble
  • Adds up the elements in each row. Returns a column vector.

    Declaration

    Swift

    public func sumRows() -> Matrix
  • Adds up the elements in each column. Returns a row vector.

    Declaration

    Swift

    public func sumColumns() -> Matrix
  • Returns the matrix determinant

    In linear algebra, the determinant is a scalar value that can be computed from the elements of a square matrix and encodes certain properties of the linear transformation described by the matrix. The determinant of a matrix A is denoted det(A), det A, or |A|. Geometrically, it can be viewed as the volume scaling factor of the linear transformation described by the matrix. This is also the signed volume of the n-dimensional parallelepiped spanned by the column or row vectors of the matrix. The determinant is positive or negative according to whether the linear mapping preserves or reverses the orientation of n-space.

    Declaration

    Swift

    public func determinant() -> BigDouble?

Minimum and maximum

Statistics

  • Calculates the mean for each of the matrix’s columns.

    Declaration

    Swift

    public func mean() -> Matrix
  • Calculates the mean for some of the matrix’s columns. Note: This returns a matrix of the same size as the original one. Any columns not in the range are set to 0.

    Declaration

    Swift

    public func mean(_ range: CountableRange<Int>) -> Matrix
  • Calculates the mean for some of the matrix’s columns. Note: This returns a matrix of the same size as the original one. Any columns not in the range are set to 0.

    Declaration

    Swift

    public func mean(_ range: CountableClosedRange<Int>) -> Matrix
  • Calculates the standard deviation for each of the matrix’s columns.

    Declaration

    Swift

    public func std() -> Matrix
  • Calculates the standard deviation for some of the matrix’s columns. Note: This returns a matrix of the same size as the original one. Any columns not in the range are set to 0.

    Declaration

    Swift

    public func std(_ range: CountableRange<Int>) -> Matrix
  • Calculates the standard deviation for some of the matrix’s columns.

    Note: This returns a matrix of the same size as the original one. Any columns not in the range are set to 0.

    Declaration

    Swift

    public func std(_ range: CountableClosedRange<Int>) -> Matrix
  • Solve any system of equations.

    Equations involving matrices and vectors of real numbers can often be solved by using methods from linear algebra. A finite set of linear equations in a finite set of variables, for example x_1, x_2,…, x_n or x, y, …, z, is called a system of linear equations or a linear system. Systems of linear equations form a fundamental part of linear algebra. Historically, linear algebra and matrix theory has been developed for solving such systems. In the modern presentation of linear algebra through vector spaces and matrices, many problems may be interpreted in terms of linear systems.

    For example, let

    2x + y - z = 8 \\ -3x - y + 2z = -11 \\ -2x + y + 2z = -3
    be a linear system. To such a system, one may associate its matrix
    M\begin{pmatrix}2 & 1 & -1\\-3 & -1 & 2 \\-2 & 1 & 2\end{pmatrix}
    and its right member vector
    v\begin{pmatrix}8\\-11\\-3\end{pmatrix}
    Let T be the linear transformation associated to the matrix M. A solution of the system (S) is a vector
    X\begin{pmatrix}x\\y\\z\end{pmatrix}
    such that$T(X)=v$`

    that is an element of the preimage of v by T. Let (S’) be the associated homogeneous system, where the right-hand sides of the equations are put to zero:

    2x + y - z = 0 \\ -3x - y + 2z = 0 \\ -2x + y + 2z = 0
    The solutions of (S’) are exactly the elements of the kernel of T or, equivalently, M. The Gaussian-elimination consists of performing elementary row operations on the augmented matrix
    M \left( \begin{array}{rrr|r}2 & 1 & -1 & 8 \\ -3 & -1 & 2 & -11 \\ -2 & 1 & 2 & -3 \end{array}\right)
    for putting it in reduced row echelon form. These row operations do not change the set of solutions of the system of equations. In the example, the reduced echelon form is
    M \left( \begin{array}{ccc|c}1 & 0 & 0 & 2 \\ 0 & 1 & 0 & 3 \\ 0 & 0 & 1 & -1 \end{array}\right)
    showing that the system (S) has the unique solution
    x = 2 \\ y = 3 \\ z = -1
    It follows from this matrix interpretation of linear systems that the same methods can be applied for solving linear systems and for many operations on matrices and linear transformations, which include the computation of the ranks, kernels, matrix inverses.

    So, you can reproduce the exact same process with:

    let m = Matrix([[2,1-1],[-3,-1,2],[-2,1,2]] as [[Double]]) // Creating the Matrix
    let s = m.solveEquationsSystem(vector: [8, -11, -3]) // Solving the system
    

    Declaration

    Swift

    public func solveEquationsSystem(vector: [Double]) throws -> Matrix

    Parameters

    vector

    The result vector

  • Creates a matrix where each element is 0.

    Declaration

    Swift

    public static func zeros(rows: Int, columns: Int) -> Matrix
  • Undocumented

    Declaration

    Swift

    public static func zeros(size: (Int, Int)) -> Matrix
  • Creates a matrix where each element is 1.

    Declaration

    Swift

    public static func ones(rows: Int, columns: Int) -> Matrix
  • Undocumented

    Declaration

    Swift

    public static func ones(size: (Int, Int)) -> Matrix
  • Creates a (square) identity matrix.

    Declaration

    Swift

    public static func identity(size: Int) -> Matrix
  • Creates a matrix of random values between 0.0 and 1.0 (inclusive).

    Declaration

    Swift

    public static func random(rows: Int, columns: Int) -> Matrix

Querying the matrix

Creating matrices

Printable

SequenceType