# 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)

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()

•  rows 

Undocumented

#### Declaration

Swift

public let rows: Int
•  columns 

Undocumented

#### Declaration

Swift

public let columns: Int

### Operations

•  inverse() 

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() 

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

•  +(_:_:) 

• 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

•  exp() 

Exponentiates each element of the matrix.

#### Declaration

Swift

public func exp() -> Matrix
•  log() 

Takes the natural logarithm of each element of the matrix.

#### Declaration

Swift

public func log() -> Matrix
•  pow(_:) 

Raised each element of the matrix to power alpha.

#### Declaration

Swift

public func pow(_ alpha: Double) -> Matrix
•  sqrt() 

Takes the square root of each element of the matrix.

#### Declaration

Swift

public func sqrt() -> Matrix
•  sum() 

Adds up all the elements in the matrix.

#### Declaration

Swift

public func sum() -> BigDouble
•  sumRows() 

Adds up the elements in each row. Returns a column vector.

#### Declaration

Swift

public func sumRows() -> Matrix
•  sumColumns() 

Adds up the elements in each column. Returns a row vector.

#### Declaration

Swift

public func sumColumns() -> Matrix
•  determinant() 

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

•  min(row:) 

Undocumented

#### Declaration

Swift

public func min(row r: Int) -> (Double, Int)
•  max(row:) 

Undocumented

#### Declaration

Swift

public func max(row r: Int) -> (Double, Int)
•  minRows() 

Undocumented

#### Declaration

Swift

public func minRows() -> Matrix
•  maxRows() 

Undocumented

#### Declaration

Swift

public func maxRows() -> Matrix
•  min(column:) 

Undocumented

#### Declaration

Swift

public func min(column c: Int) -> (Double, Int)
•  max(column:) 

Undocumented

#### Declaration

Swift

public func max(column c: Int) -> (Double, Int)
•  minColumns() 

Undocumented

#### Declaration

Swift

public func minColumns() -> Matrix
•  maxColumns() 

Undocumented

#### Declaration

Swift

public func maxColumns() -> Matrix
•  min() 

Undocumented

#### Declaration

Swift

public func min() -> (Double, Int, Int)
•  max() 

Undocumented

#### Declaration

Swift

public func max() -> (Double, Int, Int)

### Statistics

•  mean() 

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

#### Declaration

Swift

public func mean() -> Matrix
•  mean(_:) 

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
•  mean(_:) 

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
•  std() 

Calculates the standard deviation for each of the matrix’s columns.

#### Declaration

Swift

public func std() -> Matrix
•  std(_:) 

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
•  std(_:) 

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
•  solveEquationsSystem(vector:) 

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

  ⎛  2         1        -1 ⎞
M ⎜ -3        -1         2 ⎥
⎝ -2         1         2 ⎠


and its right member vector

  ⎛  8  ⎞
v ⎜ -11 ⎥
⎝ -3  ⎠


Let T be the linear transformation associated to the matrix M. A solution of the system (S) is a vector

  ⎛ x ⎞
X ⎜ y ⎥
⎝ z ⎠


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

  ⎛  2         1        -1  |  8  ⎞
M ⎜ -3        -1         2  | -11 ⎥
⎝ -2         1         2  | -3  ⎠


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

  ⎛  1        0        0  |  2 ⎞
M ⎜ 0         1        0  |  3 ⎥
⎝ 0         0        1  | -1 ⎠


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
•  zeros(rows:columns:) 

Creates a matrix where each element is 0.

#### Declaration

Swift

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

Undocumented

#### Declaration

Swift

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

Creates a matrix where each element is 1.

#### Declaration

Swift

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

Undocumented

#### Declaration

Swift

public static func ones(size: (Int, Int)) -> Matrix
•  identity(size:) 

Creates a (square) identity matrix.

#### Declaration

Swift

public static func identity(size: Int) -> Matrix
•  random(rows:columns:) 

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

•  size 

Undocumented

#### Declaration

Swift

public var size: (Int, Int) { get }
•  count 

Returns the total number of elements in the matrix.

#### Declaration

Swift

public var count: Int { get }
•  length 

Returns the largest dimension.

#### Declaration

Swift

public var length: Int { get }
•  subscript(_:_:) 

Undocumented

#### Declaration

Swift

public subscript(row: Int, column: Int) -> Double { get set }
•  subscript(_:) 

Subscript for when the matrix is a row or column vector.

#### Declaration

Swift

public subscript(i: Int) -> Double { get set }
•  subscript(row:) 

Get or set an entire row.

#### Declaration

Swift

public subscript(row r: Int) -> Matrix { get set }
•  subscript(rows:) 

Get or set multiple rows.

#### Declaration

Swift

public subscript(rows range: CountableRange<Int>) -> Matrix { get set }
•  subscript(rows:) 

Undocumented

#### Declaration

Swift

public subscript(rows range: CountableClosedRange<Int>) -> Matrix { get set }
•  subscript(rows:) 

Gets just the rows specified, in that order.

#### Declaration

Swift

public subscript(rows rowIndices: [Int]) -> Matrix { get }
•  subscript(column:) 

Get or set an entire column.

#### Declaration

Swift

public subscript(column c: Int) -> Matrix { get set }
•  subscript(columns:) 

Get or set multiple columns.

#### Declaration

Swift

public subscript(columns range: CountableRange<Int>) -> Matrix { get set }
•  subscript(columns:) 

Undocumented

#### Declaration

Swift

public subscript(columns range: CountableClosedRange<Int>) -> Matrix { get set }
•  scalar 

Useful for when the matrix is 1x1 or you want to get the first element.

#### Declaration

Swift

public var scalar: Double { get }
•  array 

Converts the matrix into a 2-dimensional array.

#### Declaration

Swift

public var array: [[Double]] { get }

### Creating matrices

•  init(rows:columns:repeatedValue:) 

Undocumented

#### Declaration

Swift

public init(rows: Int, columns: Int, repeatedValue: Double)
•  init(size:repeatedValue:) 

Undocumented

#### Declaration

Swift

public init(size: (Int, Int), repeatedValue: Double)
•  init(_:) 

Creates a matrix from an array: [[a, b], [c, d], [e, f]].

#### Declaration

Swift

public init(_ data: [[Double]])
•  init(data:) 

Creates a matrix from an array: [[a, b], [c, d], [e, f]].

#### Declaration

Swift

public init(data: [[BigDouble]])
•  init(_:range:) 

Extracts one or more columns into a new matrix.

#### Declaration

Swift

public init(_ data: [[Double]], range: CountableRange<Int>)
•  init(_:range:) 

Extracts one or more columns into a new matrix.

#### Declaration

Swift

public init(_ data: [[Double]], range: CountableClosedRange<Int>)
•  init(data:range:) 

Extracts one or more columns into a new matrix.

#### Declaration

Swift

public init(data: [[BigDouble]], range: CountableClosedRange<Int>)
•  init(data:range:) 

Extracts one or more columns into a new matrix.

#### Declaration

Swift

public init(data: [[BigDouble]], range: CountableRange<Int>)
•  init(_:isColumnVector:) 

Creates a matrix from a row vector or column vector.

#### Declaration

Swift

public init(_ contents: [Double], isColumnVector: Bool = false)
•  init(_:isColumnVector:) 

Creates a matrix containing the numbers in the specified range.

#### Declaration

Swift

public init(_ range: CountableRange<Int>, isColumnVector: Bool = false)
•  init(_:isColumnVector:) 

Undocumented

#### Declaration

Swift

public init(_ range: CountableClosedRange<Int>, isColumnVector: Bool = false)
•  init(arrayLiteral:) 

Array literals are interpreted as row vectors.

#### Declaration

Swift

public init(arrayLiteral: Double...)
•  tile(_:) 

Duplicates a row vector across “d” rows.

#### Declaration

Swift

public func tile(_ d: Int) -> Matrix
•  init(rows:columns:data:) 

Copies the contents of an NSData object into the matrix.

#### Declaration

Swift

public init(rows: Int, columns: Int, data: NSData)
•  data 

Copies the contents of the matrix into an NSData object.

#### Declaration

Swift

public var data: NSData? { get }

### Printable

•  description 

#### Declaration

Swift

public var description: String { get }

### SequenceType

•  makeIterator() 

#### Declaration

Swift

public func makeIterator() -> AnyIterator<ArraySlice<Double>>`