Matrix
public struct Matrix
extension Matrix: ExpressibleByArrayLiteral
extension Matrix: CustomStringConvertible
extension Matrix: Sequence
Simple Matrix type
Warning
Not available on LinuxMatrix 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()
-
Undocumented
Declaration
Swift
public let rows: Int
-
Undocumented
Declaration
Swift
public let columns: Int
-
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 diagonallyIn 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
-
Transpose the
Matrix
by flipping it diagonallyDeclaration
Swift
postfix static func ′ (value: Matrix) -> Matrix
Parameters
value
The
Matrix
you want to transpose
-
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 anotherDeclaration
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
-
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?
-
Undocumented
Declaration
Swift
public func min(row r: Int) -> (Double, Int)
-
Undocumented
Declaration
Swift
public func max(row r: Int) -> (Double, Int)
-
Undocumented
Declaration
Swift
public func minRows() -> Matrix
-
Undocumented
Declaration
Swift
public func maxRows() -> Matrix
-
Undocumented
Declaration
Swift
public func min(column c: Int) -> (Double, Int)
-
Undocumented
Declaration
Swift
public func max(column c: Int) -> (Double, Int)
-
Undocumented
Declaration
Swift
public func minColumns() -> Matrix
-
Undocumented
Declaration
Swift
public func maxColumns() -> Matrix
-
Undocumented
Declaration
Swift
public func min() -> (Double, Int, Int)
-
Undocumented
Declaration
Swift
public func max() -> (Double, Int, Int)
-
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 = -3be a linear system. To such a system, one may associate its matrixM\begin{pmatrix}2 & 1 & -1\\-3 & -1 & 2 \\-2 & 1 & 2\end{pmatrix}and its right member vectorv\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 vectorX\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 = 0The 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 matrixM \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 isM \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 solutionx = 2 \\ y = 3 \\ z = -1It 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
-
Undocumented
Declaration
Swift
public var size: (Int, Int) { get }
-
Returns the total number of elements in the matrix.
Declaration
Swift
public var count: Int { get }
-
Returns the largest dimension.
Declaration
Swift
public var length: Int { get }
-
Undocumented
Declaration
Swift
public subscript(row: Int, column: Int) -> Double { get set }
-
Subscript for when the matrix is a row or column vector.
Declaration
Swift
public subscript(i: Int) -> Double { get set }
-
Get or set an entire row.
Declaration
Swift
public subscript(row r: Int) -> Matrix { get set }
-
Get or set multiple rows.
Declaration
Swift
public subscript(rows range: CountableRange<Int>) -> Matrix { get set }
-
Undocumented
Declaration
Swift
public subscript(rows range: CountableClosedRange<Int>) -> Matrix { get set }
-
Gets just the rows specified, in that order.
Declaration
Swift
public subscript(rows rowIndices: [Int]) -> Matrix { get }
-
Get or set an entire column.
Declaration
Swift
public subscript(column c: Int) -> Matrix { get set }
-
Get or set multiple columns.
Declaration
Swift
public subscript(columns range: CountableRange<Int>) -> Matrix { get set }
-
Undocumented
Declaration
Swift
public subscript(columns range: CountableClosedRange<Int>) -> Matrix { get set }
-
Useful for when the matrix is 1x1 or you want to get the first element.
Declaration
Swift
public var scalar: Double { get }
-
Converts the matrix into a 2-dimensional array.
Declaration
Swift
public var array: [[Double]] { get }
-
Undocumented
Declaration
Swift
public init(rows: Int, columns: Int, repeatedValue: Double)
-
Undocumented
Declaration
Swift
public init(size: (Int, Int), repeatedValue: Double)
-
Creates a matrix from an array: [[a, b], [c, d], [e, f]].
Declaration
Swift
public init(_ data: [[Double]])
-
Creates a matrix from an array: [[a, b], [c, d], [e, f]].
Declaration
Swift
public init(data: [[BigDouble]])
-
Extracts one or more columns into a new matrix.
Declaration
Swift
public init(_ data: [[Double]], range: CountableRange<Int>)
-
Extracts one or more columns into a new matrix.
Declaration
Swift
public init(_ data: [[Double]], range: CountableClosedRange<Int>)
-
Extracts one or more columns into a new matrix.
Declaration
Swift
public init(data: [[BigDouble]], range: CountableClosedRange<Int>)
-
Extracts one or more columns into a new matrix.
Declaration
Swift
public init(data: [[BigDouble]], range: CountableRange<Int>)
-
Creates a matrix from a row vector or column vector.
Declaration
Swift
public init(_ contents: [Double], isColumnVector: Bool = false)
-
Creates a matrix containing the numbers in the specified range.
Declaration
Swift
public init(_ range: CountableRange<Int>, isColumnVector: Bool = false)
-
Undocumented
Declaration
Swift
public init(_ range: CountableClosedRange<Int>, isColumnVector: Bool = false)
-
Array literals are interpreted as row vectors.
Declaration
Swift
public init(arrayLiteral: Double...)
-
Duplicates a row vector across “d” rows.
Declaration
Swift
public func tile(_ d: Int) -> Matrix
-
Copies the contents of an NSData object into the matrix.
Declaration
Swift
public init(rows: Int, columns: Int, data: NSData)
-
Copies the contents of the matrix into an NSData object.
Declaration
Swift
public var data: NSData? { get }
-
Declaration
Swift
public var description: String { get }
-
Declaration
Swift
public func makeIterator() -> AnyIterator<ArraySlice<Double>>