# Matrices¶

The full docs are below but I’ll touch on some highlights:

• depends on vector. Access the row-major indexed flat array via matrix.flat. This means that any function that takes a flat array can be applied to a matrix.
• Implements some complex math: solve, dot, svd, and inv
• has some nice functions for image, including functions to show and save images.

Note

* is an element-wise multiplication. There is no matrix multiplication operator because we ran into scope issues. Instead, use A.dot(x)

Note

The function to show/save images rely on Python, PYTHON_PATH and the pylab stack.

Warning

A.flat gives access to the entire array which swix depends uses to get around typing annoyances. Call max(A.flat) to find the maximum element in the entire array.

## Docs¶

class matrix.matrix[source]

This class depends on vector where possible since matrix is really a flat and row-major array. To implement a 2D matrix, I just return select indices when indexing.

Note

Row major order differs from Matlab and it’s column major order. While the flat indexing differs, NumPy, Matlab and swix all index the same with two indices. ie, x[1,3] will return similar values in all three.

I = 'inverse'[source]

Returns the inverse of the matrix. Calls complex_math.inv

T = 'transpose'[source]

Returns the transpose of the matrix. Call helper_functions.transpose

columns = 'Int'[source]

Number of columns

copy()[source]

Copies the matrix.

Return type: A copy of the array.
>>> x = arange(4).reshape((2,2))
>>> assert(x ~== x.copy())

dot(x)[source]

Matrix multiplication with another matrix.

Parameters: x (matrix, vector) – The lhs of the matrix. matrix, vector. The matrix multiplication of the two input arguments. The return type mirrors the type of the input x

Callable with A.dot(x) and dot(A, x) where A is a matrix and x an vector or matrix.

flat = 'vector'[source]

The base vector stored in row-major order. Is of type vector.vector; any function that takes an vector can take this element.

index(one, two)[source]

Indexes with two numbers; range<int>, vector or int. Includes negative indexing like Python

Use x[1, "all"] to access an entire row or column.

Also possible to use boolean indexing. x[x < 0] <- 0 is the primary use case for this.

Warning

Assumes wholly negative or positive. Indexes like array(-1, 0, 1) aren’t supported.

Parameters: one (Int, Range, vector, String) – The row selector. two (Int, Range, vector, String) – The column selector. matrix

Note

Use x[3, 4] to index, not the function name.

>>> x = arange(9).reshape((3,3))
# x = [0 1 2; 3 4 5; 6 7 8]
>>> assert(x[0,1] == 1)
>>> assert(x[0..<2, 0..<3] ~== array("0 1 2; 3 4 5")
>>> assert(x[arange(2), arange(3)] ~== array("0 1 2; 3 4 5")
>>> assert(x[0, "all"] ~== array(0, 1, 2))
>>> x[x < 4] <- 0
>>> assert(x[x < 4] ~== zeros(4))


np.indexing

index_diag(string)[source]

Gets or sets the diagonal.

Parameters: string (String) – This asserts that this input string must be “diag”. vector

Gets or sets the diagonal of a matrix.

>>> x = arange(9).reshape((3,3))
>>> x["diag"] = array(-1, -2, -3)
>>> assert(x["diag"] = array(-1, -2, -3))
>>> print(x)
# prints [-1 1 2; 3 -2 5; 6 7 -3]

index_flat(idx)[source]

Indexes in the row-major flat array.

Parameters: idx (vector) – In row major order, the elements to take. vector. Indexes matrix.flat in row-major order.

Note

Use x[array(1, 2, 3, x.shape.0+1)] to index, not the function name.

>>> x = arange(9).rehshape((3,3))
>>> assert(x[array(0, 3, 6)] ~== array(0, 3, 6))


np.flat

n = 'Int'[source]

Number of elements

rows = 'Int'[source]

Number of rows

shape = '(rows, columns)'[source]

The shape of the matrix (in typical mathematical language)

tril(x)[source]

Return the indices to the lower part of the array.

Parameters: x (matrix) – The matrix you wish to get the lower part of.
>>> x = arange(9).reshape((3,3))
>>> assert(x[triu(x)] ~== array(3, 6, 7))


np.tril

triu(x)[source]

Return the indices to the upper part of the array.

Parameters: x (matrix) – The matrix you wish to get the lower part of.
>>> x = arange(9).reshape((3,3))
>>> assert(x[triu(x)] ~== array(1, 2, 5))


np.triu

class matrix.simple_math[source]

Often, a function is applied to every element. Uses vector.simple_math. This applies a function to every element and simply calls function(x.flat).

abs(x)[source]
Parameters: x (matrix) – Applies the function to every element.
ceil(x)[source]
Parameters: x (matrix) – Applies the function to every element.
cos(x)[source]
Parameters: x (matrix) – Applies the function to every element.
floor(x)[source]
Parameters: x (matrix) – Applies the function to every element.
log(x)[source]
Parameters: x (matrix) – Applies the function to every element.
mean(x, axis=-1)[source]
Parameters: x (matrix) – dim (Int) – The dimension to which compute the average over. Returns the mean along each dimension
pow(x, power)[source]
Parameters: x (matrix) – power (Double) – Applies the function to every element.
prod(x, axis=-1)[source]

Find the product of each row/column of a matrix.

Parameters: x (matrix) – The matrix. vector. The product along the columns or rows.

np.prod

round(x)[source]
Parameters: x (matrix) – Applies the function to every element.
sign(x)[source]
Parameters: x (matrix) – Applies the function to every element.
sin(x)[source]
Parameters: x (matrix) – Applies the function to every element.
sqrt(x)[source]
Parameters: x (matrix) – Applies the function to every element.
sum(x, axis=-1)[source]

Perform the sum over a given axis.

Parameters: x (matrix) – axis (Int) – Assumed to be either 0 or 1. Finds the sum of all values that are not in the axis. vector
>>> var x = arange(6).reshape((2,3))
>>> assert(sum(x, dim:0) ~== array(3, 5, 7))
>>> assert(sum(x, dim:1) ~== array(3, 12))


np.sum

tan(x)[source]
Parameters: x (matrix) – Applies the function to every element.

### matrix class¶

class matrix.matrix[source]

This class depends on vector where possible since matrix is really a flat and row-major array. To implement a 2D matrix, I just return select indices when indexing.

Note

Row major order differs from Matlab and it’s column major order. While the flat indexing differs, NumPy, Matlab and swix all index the same with two indices. ie, x[1,3] will return similar values in all three.

I = 'inverse'[source]

Returns the inverse of the matrix. Calls complex_math.inv

T = 'transpose'[source]

Returns the transpose of the matrix. Call helper_functions.transpose

columns = 'Int'[source]

Number of columns

copy()[source]

Copies the matrix.

Return type: A copy of the array.
>>> x = arange(4).reshape((2,2))
>>> assert(x ~== x.copy())

dot(x)[source]

Matrix multiplication with another matrix.

Parameters: x (matrix, vector) – The lhs of the matrix. matrix, vector. The matrix multiplication of the two input arguments. The return type mirrors the type of the input x

Callable with A.dot(x) and dot(A, x) where A is a matrix and x an vector or matrix.

flat = 'vector'[source]

The base vector stored in row-major order. Is of type vector.vector; any function that takes an vector can take this element.

index(one, two)[source]

Indexes with two numbers; range<int>, vector or int. Includes negative indexing like Python

Use x[1, "all"] to access an entire row or column.

Also possible to use boolean indexing. x[x < 0] <- 0 is the primary use case for this.

Warning

Assumes wholly negative or positive. Indexes like array(-1, 0, 1) aren’t supported.

Parameters: one (Int, Range, vector, String) – The row selector. two (Int, Range, vector, String) – The column selector. matrix

Note

Use x[3, 4] to index, not the function name.

>>> x = arange(9).reshape((3,3))
# x = [0 1 2; 3 4 5; 6 7 8]
>>> assert(x[0,1] == 1)
>>> assert(x[0..<2, 0..<3] ~== array("0 1 2; 3 4 5")
>>> assert(x[arange(2), arange(3)] ~== array("0 1 2; 3 4 5")
>>> assert(x[0, "all"] ~== array(0, 1, 2))
>>> x[x < 4] <- 0
>>> assert(x[x < 4] ~== zeros(4))


np.indexing

index_diag(string)[source]

Gets or sets the diagonal.

Parameters: string (String) – This asserts that this input string must be “diag”. vector

Gets or sets the diagonal of a matrix.

>>> x = arange(9).reshape((3,3))
>>> x["diag"] = array(-1, -2, -3)
>>> assert(x["diag"] = array(-1, -2, -3))
>>> print(x)
# prints [-1 1 2; 3 -2 5; 6 7 -3]

index_flat(idx)[source]

Indexes in the row-major flat array.

Parameters: idx (vector) – In row major order, the elements to take. vector. Indexes matrix.flat in row-major order.

Note

Use x[array(1, 2, 3, x.shape.0+1)] to index, not the function name.

>>> x = arange(9).rehshape((3,3))
>>> assert(x[array(0, 3, 6)] ~== array(0, 3, 6))


np.flat

n = 'Int'[source]

Number of elements

rows = 'Int'[source]

Number of rows

shape = '(rows, columns)'[source]

The shape of the matrix (in typical mathematical language)

tril(x)[source]

Return the indices to the lower part of the array.

Parameters: x (matrix) – The matrix you wish to get the lower part of.
>>> x = arange(9).reshape((3,3))
>>> assert(x[triu(x)] ~== array(3, 6, 7))


np.tril

triu(x)[source]

Return the indices to the upper part of the array.

Parameters: x (matrix) – The matrix you wish to get the lower part of.
>>> x = arange(9).reshape((3,3))
>>> assert(x[triu(x)] ~== array(1, 2, 5))


np.triu

### Initing¶

This is a file, not an actual class.

class matrix.initing[source]
array(matlab_like_string)[source]

An array from a matlab like string.

Parameters: matlike_like_string – matrix

Interpets the string as a matrix, matlab style. ; is interpets as a new row.

Warning

This currently only works with one digit positive numbers. Negative numbers and multiple digit numbers throw it for a loop. I would recommend using array(Double...).reshape((M,N)) instead.

>>> assert(array("1 2; 3 4") ~== array(1, 2, 3, 4).reshape((2,2))


np.matrix

eye(N)[source]

Makes the identity matrix.

Parameters: N (Int) – The size of the array will be N x N matrix. An identity matrix.

np.eye

meshgrid(x, y)[source]

Makes a mesh out of two vectors.

Parameters: x (vector) – One set of elements. y (vector) – Another set of elements. (matrix, matrix).

This function evaulates every possible combination of x and y. Very similar to NumPy’s meshgrid.

>>> x, y = meshgrid(array(1, 2), array(3, 4))
>>> print(x)
# prints [1 2; 1 2]
>>> print(y)
# prints [3 3; 4 4]


np.meshgrid

ones(shape)[source]

Makes a matrix full of ones.

Parameters: shape ((Int, Int)) – The shape of the new matrix. (rows, columns) matrix
>>> assert(ones((2,2)) ~== ones(4).reshape((2,2)))

rand(x)[source]
Parameters: x (matrix) – Applies the function to every element.
randn(x)[source]
Parameters: x (matrix) – Applies the function to every element.
reshape(x, shape)[source]

Reshapes to the specified size.

Parameters: x (vector) – An vector shape ((Int, Int)) – The size of the new matrix A resized matrix.
zeros(shape)[source]

Makes a matrix full of zeros.

Parameters: shape ((Int, Int)) – The shape of the new matrix. (rows, columns) matrix
>>> assert(zeros((2,2)) ~== zeros(4).reshape((2,2)))

zeros_like(x)[source]

A matrix like the other matrix.

Parameters: x (matrix) – The matrix to imitate. matrix
>>> x = array(1, 2, 3, 4).reshape((2,2))
>>> assert(zeros_like(x) ~== zeros((2,2)))


np.zeros_like

### Helper functions¶

class matrix.helper_functions[source]
argwhere(idx)[source]

Sees where a condition applies.

Parameters: idx (matrix) – A matrix of zeros and ones. Normally indicates where some condition is true. vector. Returns the indicies where idx is not zero. Useful with comparison operators which return an array of 0’s and 1’s.
det(x)[source]

Estimate the determinant of a matrix.

Parameters: x (matrix) – The matrix to compute the determinant of. Double

diag(x)[source]

Make an array with the specified diagonal.

Parameters: x (vector) – The diagonal of the new array. matrix
>>> var x = diag(array(ones(3)))
>>> assert(x ~== eye(3))

fliplr(x)[source]

Flips each row.

Parameters: x (matrix) – The array to flip. The flipped matrix.

Implemented through cv.flip

>>> x = array("1 2; 3 4")
>>> assert(fliplr(x) ~== array("2 1; 4 3"))

flipud(x)[source]

Flips each column.

Parameters: x (matrix) – The array to flip. The flipped matrix.

Implemented through cv.flip

>>> x = array("1 2; 3 4")
>>> assert(fliplr(x) ~== array("3 4; 1 2"))

kron(a, b)[source]

Find the Kronecker product between two matrices.

Parameters: a (matrix) – The first term for kron. b (matrix) – The second term in kron.

norm(x, ord=2)[source]

Find the Matrix norm of a matrix.

Parameters: x (matrix) – Finds the norm of this matrix. ord (Int or string.) – Assumed to be one of “fro”, -2, -1, 1 or 2 Double. The specific norm.

Note

Almost an exact copy of np.linalg.norm.

ones_like(x)[source]

Makes an matrix like another matrix.

Parameters: x (vector) – The array to imitate.
>>> var x = array(3, 8, 2, 1).reshape((2,2))
>>> assert(ones_like(x) ~== array(1, 1, 1, 1).reshape((2,2)))


np.ones_like

println(x, prefix='matrix([', postfix='])', newline='\n', format='%.3f', printWholeMatrix=False)[source]

Prints the matrix.

Note

Can be called with either print(x) or println(x)

Parameters: x (matrix) – The matrix to print. prefix (String) – The prefix. postfix (String) – The postfix. newline (String) – The newline character. format (Bool) – The format, C style. printWholeMatrix – If true, prints every element.
rot90(x, k=1)[source]

Rotate the given matrix 90 degrees counter-clockwise. Do it k times.

Warning

k is assumed to be 1, 2 or 3

Parameters: x (matrix) – The matrix to rotate. matrix

np.rot90

transpose(x)[source]

Finds the transpose.

Parameters: x (matrix) – A source matrix. The transpose of the matrix.

### Operators¶

This is a file, not an actual class.

class matrix.operators[source]
assignment_operator(lhs, rhs)[source]

Assign select values of a matrix to a constant value.

Parameters: lhs (matrix) – The matrix to assign to. rhs (Double) – The value to fill.
>>> x = ones((4,3))
>>> x[0..<2, 0..<2] <- 5
>>> # x ~== [5, 5, 1, 1;
>>> #        5, 5, 1, 1;
>>> #        1, 1, 1, 1]

element_operators(lhs, rhs)[source]

Element wise artithmetic operators.

Parameters: lhs (Double, matrix) – The left hand side rhs (Double, matrix) – The right hand side

The operators + - * / % += -= *= /= < > <= >= == !== all work element wise and act similar to scalars.

Note

Callable through the natural operators (+, -, etc).

Note

== and !== see when two arrays are exactly equal for the incredibly percise doubles. I recommend using abs(x-y)<1e-9.

np.operators

equality(x, y)[source]

Sees if two matrices are approximately equal.

Parameters: x (matrix) – y (matrix) – Bool. true only if the two arrays are approximately equal.

Note

Callable through ~==

>>> assert(array(0, 1) ~== arange(2))


numbers.close

solve(A, b)[source]

Solves a system of eqautions similar to Matlab’s backslash.

Parameters: A (matrix) – When multplied with x, this is what the equation equals. b (vector) – What the equation equals. vector

Solves for x in $$Ax=b$$. The same as right-multiplying by the inverse but much faster.

Note

Only works for N x N matrices. Doesn’t have a least squares solution yet.

Note

Also callable through !/

### Simple Math¶

This is a file, not an actual class.

class matrix.simple_math[source]

Often, a function is applied to every element. Uses vector.simple_math. This applies a function to every element and simply calls function(x.flat).

abs(x)[source]
Parameters: x (matrix) – Applies the function to every element.
ceil(x)[source]
Parameters: x (matrix) – Applies the function to every element.
cos(x)[source]
Parameters: x (matrix) – Applies the function to every element.
floor(x)[source]
Parameters: x (matrix) – Applies the function to every element.
log(x)[source]
Parameters: x (matrix) – Applies the function to every element.
mean(x, axis=-1)[source]
Parameters: x (matrix) – dim (Int) – The dimension to which compute the average over. Returns the mean along each dimension
pow(x, power)[source]
Parameters: x (matrix) – power (Double) – Applies the function to every element.
prod(x, axis=-1)[source]

Find the product of each row/column of a matrix.

Parameters: x (matrix) – The matrix. vector. The product along the columns or rows.

np.prod

round(x)[source]
Parameters: x (matrix) – Applies the function to every element.
sign(x)[source]
Parameters: x (matrix) – Applies the function to every element.
sin(x)[source]
Parameters: x (matrix) – Applies the function to every element.
sqrt(x)[source]
Parameters: x (matrix) – Applies the function to every element.
sum(x, axis=-1)[source]

Perform the sum over a given axis.

Parameters: x (matrix) – axis (Int) – Assumed to be either 0 or 1. Finds the sum of all values that are not in the axis. vector
>>> var x = arange(6).reshape((2,3))
>>> assert(sum(x, dim:0) ~== array(3, 5, 7))
>>> assert(sum(x, dim:1) ~== array(3, 12))


np.sum

tan(x)[source]
Parameters: x (matrix) – Applies the function to every element.

### Complex math¶

This is a file, not an actual class.

class matrix.complex_math[source]
dot(A, x)[source]

Matrix multiplication between two matrices.

Parameters: A (matrix) – The lhs. x (matrix, vector) – The rhs matrix.

Performs a matrix multiplication between two matrices.

Note

Also callable through dot(A, x) and A.dot(x)

np.dot, matrix.dot, operators.dot, Matrix multiplication

eig(x)[source]

Find the eigenvaleus of a matrix.

Parameters: x (matrix) – The matrix to find the eigenvalues of. the eigenvalues the matrix.

Note

This function does not find any eigenvectors (and should but bugs).

inv(x)[source]

Find the inverse of a matrix.

Parameters: x (matrix) – Finds the inverse of this matrix. $$x^{-1}$$

Finds the inverse of the matrix; can be expensive time-wise!

pinv(x)[source]

Finds the Moore-Penrose pseudoinverse.

Parameters: x (matrix) – Finds the inverse of this matrix. matrix
rank(x)[source]

Compute the matrix rank of a matrix.

Parameters: x (matrix) – The matrix to compute the rank of. Double. The rank of the matrix.

solve(A, b)[source]

Solve a system of linear equations.

Parameters: A (matrix) – When multplied with x, this is what the equation equals. b (vector) – What the equation equals. vector

Solves for x in $$Ax=b$$. The same as right-multiplying by the inverse but much faster.

Note

Only works for N x N matrices. Doesn’t have a least squares solution yet.

Note

Also callable through !/

svd(x, compute_uv=True)[source]

Compute the singular value decomposition.

Parameters: x (matrix) – The input to the singular value decomposition. compute_uv (Bool) – Compute U and V. (matrix, vector, matrix)

Finds a factorization such that $$x = U S V$$.

### Images¶

This is a file, not an actual class.

class matrix.images[source]
RGBAToUIImage(r, g, b, a)[source]

Convert the RGBA color planes into a UIImage

Parameters: r (matrix) – The red color plane. g (matrix) – The green color plane. b (matrix) – The blur color plane. a (matrix) – The alpha color plane. UIImage

Note

Commented out in swix/matrix/image.swift as UIKit doesn’t compile for MacOSX

UIImageToRGBAImage(image)[source]

Convert an RGBA UIImage into 4 different arrays corresponding to the RGBA color planes.

Parameters: image (UIImage) – The image to convert. matrix, matrix, matrix, matrix.

Note

Commented out in swix/matrix/image.swift as UIKit doesn’t compile for MacOSX.

imshow(x)[source]

Shows a matrix using Python.

Parameters: x (matrix) – The matrix you want to see.

Shows the matrix. Relies on Python being found at PYTHON_PATH and pylab stack being installed

mpl.imshow

resizeImage(image, shape)[source]

Resize an image to the given shape.

Parameters: image (UIImage) – The image to resize. shape ((Int, Int)) – The desired size; (vertical_length, horizontal_length)

Note

Commented out in swix/matrix/image.swift as UIKit doesn’t compile for MacOSX

rgb2hsv(r, g, b)[source]

Converts RGB values to HSV values.

Parameters: r (matrix) – The red color plane. g (matrix) – The green color plane. b (matrix) – The blue color plane. (matrix, matrix, matrix). Returns the HSV color planes.

Note

This function isn’t optimized.

rgb2hsv_vplane(r, g, b)[source]

Converts a set of RGB color values to the HSV v plane only. Since $$v = \max(r, g, b)$$, this function is optimized.

Parameters: r (matrix) – The red color plane. g (matrix) – The blue color plane. b (matrix) – The green color plane. matrix. The v plane.
savefig(x, filename, save=True, show=False)[source]

Saves a figure using Python.

Parameters: x (matrix) – The matrix you want to see. filename (String) – The filename you want to save at.

Saves the matrix. Relies on Python being found at PYTHON_PATH and pylab stack being installed