Source code:
Q-Matrix.js
Grid of numbers
A matrix is just a grid of numbers; rows and columns containing values. Matrices can be of any size. Here’s an example of a 3 × 2 matrix. It is 3 columns wide and 2 rows tall, containing the values 1 through 6.
| 1 | 2 | 3 |
| 4 | 5 | 6 |
When describing the dimensions of a matrix we always specify the number of rows first, then the number of columns. The above is an example of a 3 × 2 matrix, while below is a matrix containing similar data, but in a 2 × 3 configuration.
| 1 | 2 |
| 3 | 4 |
| 5 | 6 |
Order matters
Q thinks about matrices in row-major order. This means we read the values just as they are ordered above, starting with the top-most row, reading values from left to right, then proceeding to the next row down and repeating that process. Our choice of row-major order makes reading and writing matrix values more akin to reading and writing in English; easier to type and program here.
|
Row-major order. | ||||||
|
Column-major order. |
Vectors are slices
While a matrix is a two-dimensional grid of numbers, a vector is more like a slice of numbers—such as a “skinny” matrix that is only one column wide, or a “flat” matrix that is only one row high. Let’s look at some examples of matrices that are simultaneously vectors.
|
Any “flat” matrix is
a row vector. |
||||
|
Any “skinny” matrix is
a column vector. |
||||
|
But matrices with
more than one column or more than one row are not vectors. |
While the above 2 × 2 matrix is not a vector, you could say that it contains vectors: Two column vectors or two row vectors.
Because vectors are just a type of matrix we can add them, multiply them, and so on—just like any other matrix. Vectors will play a prominent role in defining qubits and expressing the state of a quantum circuit.
Complex numbers
Instead of just storing
regular old numbers,
our matrices are geared to store
complex numbers.
(This is because
qubits are really just a pair of
complex numbers
that we store in a 1 × 2 matrix.
So, yes—the example matrices above are actually all larger than qubits are!)
In general, we don’t even have to think about
the fact that our matrices are storing complex numbers
because
Q.Matrix is
happy to accept regular JavaScript Number values as input—and
Q.ComplexNumber
will silently handle the conversion for us.
Constructor
Matrix
Function([ size: Number ] or [ width: Number, height: Number ] or [ rows: arguments ]) => Q.Matrix
The Matrix class creates and operates on matrices of arbitrary dimensions.
This is in contrast to some popular graphics libraries
which optimize for specific sizes of matrices—with corresponding class names like
Matrix3 (for 3 × 3 matrices) or Matrix4 (for 4 × 4 matrices).
Q, meanwhile, is much more flexible.
The constructor expects an argument list of
equal-length arrays where each array represents a row of column values.
Matrix then automatically determines the dimensions based on the number of
arguments (rows) and length of each row (number of columns).
The constructor will throw an error if the row lengths are not equal.
Upon creation Matrix converts all argument values of type Number
to Q.ComplexNumber instances.
Currently Matrix does not support recursion;
a matrix cannot contain matrices as values.
A matrix also cannot change its dimensions, making destructive properties
that yield matrices of a different size (like multiply$, for example) impossible.
var a = new Q.Matrix(
[ 1, 2, 3 ],
[ 4, 5, 6 ])
| 1 | 2 | 3 |
| 4 | 5 | 6 |
-
- rows
ArrayThe list of suppliedarguments. -
- columns
ArrayThe list of getters and setters that operate on the rows property to appear as if this property contained actual values. -
- index
NumberAn identification number assigned to the instance, used for minding the total number of instances created.
Import and export formats
Getting data in and out of any system can be laborious.
With that in mind, Q.Matrix comes with helper methods for
importing and exporting the following common formats:
- Comma separated values (CSV)
- Tab separated values (TSV)
- Arbitrary character separated values (XSV)
- HTML table code
Static properties
-
- help
Function ⇒ StringCalls and returns the value ofQ.help, passingQ.Matrixas the argument. -
- index
NumberThe number of instances created so far.
Constants and constant creation
-
- constants
ObjectConstants are appended directly to theQ.Matrixobject. For convenience they are also appended to thisQ.Matrix.constants object to make looking up constants in the JavaScript console trivial, and to make iterating across all constants convenient via functions likeObject.entries,Object.keys,Object.values, and so on. The intention that a property act as a constant is signaled by its labelling in all-uppercase. -
- createConstant
Function( key: String, value: * )Appends a property named bykeywith a value ofvalueto both theMatrixobject and itsconstantsproperty. -
- createConstants
Function( … )Expects an even number of arguments. Will use each pair in the sequence of arguments to callcreateConstant.
Constants — Example matrices
-
- IDENTITY_2X2
Q.MatrixInitialized asQ.Matrix.createIdentity( 2 ). Described by the following matrix:1 0 0 1 -
- IDENTITY_3X3
Q.MatrixInitialized asQ.Matrix.createIdentity( 3 ). Described by the following matrix:1 0 0 0 1 0 0 0 1 -
- IDENTITY_4X4
Q.MatrixInitialized asQ.Matrix.createIdentity( 4 ). Described by the following matrix:1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 -
- CONSTANT0_2X2
Q.MatrixInitialized as
Described by the following matrix:new Q.Matrix( [ 1, 1 ], [ 0, 0 ])1 1 0 0 -
- CONSTANT1_2X2
Q.MatrixInitialized as
Described by the following matrix:new Q.Matrix( [ 0, 0 ], [ 1, 1 ])0 0 1 1 -
- NEGATION_2X2
Q.MatrixInitialized as
Described by the following matrix:new Q.Matrix( [ 0, 1 ], [ 1, 0 ])0 1 1 0 -
- TEST_MAP_9X9
Q.MatrixInitialized as
Described by the following matrix:new Q.Matrix( [ 11, 21, 31, 41, 51, 61, 71, 81, 91 ], [ 12, 22, 32, 42, 52, 62, 72, 82, 92 ], [ 13, 23, 33, 43, 53, 63, 73, 83, 93 ], [ 14, 24, 34, 44, 54, 64, 74, 84, 94 ], [ 15, 25, 35, 45, 55, 65, 75, 85, 95 ], [ 16, 26, 36, 46, 56, 66, 76, 86, 96 ], [ 17, 27, 37, 47, 57, 67, 77, 87, 97 ], [ 18, 28, 38, 48, 58, 68, 78, 88, 98 ], [ 19, 29, 39, 49, 59, 69, 79, 89, 99 ])11 21 31 41 51 61 71 81 91 12 22 32 42 52 62 72 82 92 13 23 33 43 53 63 73 83 93 14 24 34 44 54 64 74 84 94 15 25 35 45 55 65 75 85 95 16 26 36 46 56 66 76 86 96 17 27 37 47 57 67 77 87 97 18 28 38 48 58 68 78 88 98 19 29 39 49 59 69 79 89 99
Static inspection
-
- isMatrixLike
Function( object: * ) ⇒ BooleanReturnstrueifobjectis an instance ofQ.Matrixor ifQ.Matrixis inobject’s prototype chain, otherwise returnsfalse. -
- getWidth
Function( m: Q.Matrix ) ⇒ NumberReturns the number of columns in this matrix. -
- getHeight
Function( m: Q.Matrix ) ⇒ NumberReturns the number of rows in this matrix. -
- haveEqualDimensions
Function( a: Q.Matrix, b: Q.Matrix ) ⇒ BooleanReturnstrueif both matrices have the same number of rows and the same number of columns, otherwise returnsfalse. -
- isWithinRange
Function( n: Number, minimum: Number, maximum: Number ) ⇒ BooleanReturnstrueifnis an integer, and is greater than or equal tominimum, and is less than or equal tomaximum, otherwise returnsfalse. Used to determine if a value is a valid row or column number.
Creation from description
-
- createSquare
Function([ size: Number = 2[, f: Function = function(){ return 0 }]]) ⇒ Q.MatrixCreates a square matrix of width and height equal tosize.fis invoked for each cell of the matrix and is passed two arguments,x: Numberandy: Number, which correspond to the address of the cell. The result offis then assigned to that cell. Returns the resulting matrix. -
- createZero
Function( size: Number ) ⇒ Q.MatrixCallscreateSquarewith the passedsizeargument, but no function argument, to yield a matrix of all zeros. Returns the resulting matrix. -
- createOne
Function( size: Number ) ⇒ Q.MatrixCallscreateSquarewith the passedsizeargument, and anfargument that invariably returns1, to yield a matrix of all ones. Returns the resulting matrix. -
- createIdentity
Function( size: Number ) ⇒ Q.MatrixCallscreateSquarewith the passedsizeargument, and anfargument that yields an identity matrix. Returns the resulting matrix.
Creation from data import
-
- fromArray
Function( array: Array ) ⇒ Q.MatrixIngests matrix data from anArrayof values where each element represents a row that is itself anArrayof values, and returns the result. Note how this differs from theMatrixconstructor which uses the function’sArray-like arguments list directly. -
- fromXsv
Function( input: String, rowSeparator: String, valueSeparator: String ) ⇒ Q.MatrixIngests matrix data from aStringof values that are sepearated in to rows byrowSeparatorand separated in to values (columns) byvalueSeparator, and returns the result. -
- fromCsv
Function( csv: String ) ⇒ Q.MatrixIngests matrix data from aStringof comma-separated-values and returns the result. -
- fromTsv
Function( tsv: String ) ⇒ Q.MatrixIngests matrix data from aStringof tab-separated-values and returns the result. -
- fromHtml
Function( html: String ) ⇒ Q.MatrixIngests matrix data from aStringof HTML table code and returns the result.
Static maths
-
- add
Function( a: Q.Matrix, b: Q.Matrix ) ⇒ Q.MatrixAdds the two supplied matrices together and returns the result. -
- multiplyScalar
Function( a: Q.Matrix, b: Number ) ⇒ Q.MatrixMultiplies the supplied matrix by the supplied scalar and returns the result. -
- multiply
Function( a: Q.Matrix, b: Q.Matrix ) ⇒ Q.MatrixMultiplies the two supplied matrices together and returns the result. -
- multiplyTensor
Function( a: Q.Matrix, b: Q.Matrix ) ⇒ Q.MatrixReturns thetensor productof the two supplied matrices.
Prototype properties
Self inspection
-
- isValidRow
Function( rowIndex: Number ) ⇒ BooleanReturns true ifrowIndexis greater than or equal to zero and is less than the height of this matrix, otherwise returnsfalse. Will return aBooleanvalue, thereby halting “Fluent interface” method chaining for this instance. -
- isValidColumn
Function( columnIndex: Number ) ⇒ BooleanReturns true ifcolumnIndexis greater than or equal to zero and is less than the width of this matrix, otherwise returnsfalse. Will return aBooleanvalue, thereby halting “Fluent interface” method chaining for this instance. -
- isValidAddress
Function( x: Number, y: Number ) ⇒ BooleanReturnstrueifxis a valid row index andyis a valid column index, otherwise returnsfalse. Will return aBooleanvalue, thereby halting “Fluent interface” method chaining for this instance. -
- getWidth
Function ⇒ NumberCalls and returns the value ofQ.Matrix.getWidth, passing itself as the argument. Will return aNumbervalue, thereby halting “Fluent interface” method chaining for this instance. -
- getHeight
Function ⇒ NumberCalls and returns the value ofQ.Matrix.getHeight, passing itself as the argument. Will return aNumbervalue, thereby halting “Fluent interface” method chaining for this instance.
Data export (non-destructive)
-
- read
Function( x: Number, y: Number ) ⇒ Q.ComplexNumberReturns the value of this matrix’s cell at rowyand columnx. Equivalent tothis.columns[ x ][ y ]orthis.rows[ y ][ x ]but with safety mechanisms. Will return aNumbervalue, thereby halting “Fluent interface” method chaining for this instance. -
- clone
Function ⇒ Q.MatrixReturns a new instance with the value forrowscopied from this instance. The constructor will populate the values forcolumnsas well. -
- toArray
Function ⇒ ArrayReturns the value of this instance’srowsproperty. Will return anArrayvalue, thereby halting “Fluent interface” method chaining for this instance. -
- toXsv
Function( rowSeparator: String, valueSeparator: String ) ⇒ StringReturns the value of this matrix expressed as aStringdelimited by the supplied arguments. Will return aStringvalue, thereby halting “Fluent interface” method chaining for this instance. -
- toCsv
Function ⇒ StringCreates a comma-separated-values table and returns it as aString. Will return aStringvalue, thereby halting “Fluent interface” method chaining for this instance. -
- toTsv
Function ⇒ StringCreates a tab-separated-values table and returns it as aString. Will return aStringvalue, thereby halting “Fluent interface” method chaining for this instance. -
- toHtml
Function ⇒ StringCreates HTML table code and returns it as aString. Will return aStringvalue, thereby halting “Fluent interface” method chaining for this instance. -
- toDom
Function ⇒ DocumentFragmentArriving soon. Will return aDocumentFragmentvalue, thereby halting “Fluent interface” method chaining for this instance.
Data import (destructive)
-
- write$
Function( x: Number, y: Number, n: Number or Q.ComplexNumber ) ⇒ Q.MatrixWrites a value,n, to the specified cell address of this matrix. Equivalent tothis.columns[ x ][ y ] = n, orthis.rows[ y ][ x ] = n, but with safety checks. -
- copy$
Function( m: Q.Matrix ) ⇒ Q.MatrixCopies the value forrowsfrom the supplied argument,m, ifmis a matrix of equal dimensions to this instance, otherwise returnsQ.error. -
- fromArray$
Function( array: Array ) ⇒ Q.MatrixPasses the suppliedarrayargument to thefromArraystatic method, then usescopy$to copy that result in to this instance. -
- fromCsv$
Function( csv: String ) ⇒ Q.MatrixPasses the suppliedcsvargument to thefromCsvstatic method, then usescopy$to copy that result in to this instance. -
- fromTsv$
Function( tsv: String ) ⇒ Q.MatrixPasses the suppliedtsvargument to thefromTsvstatic method, then usescopy$to copy that result in to this instance. -
- fromHtml$
Function( html: String ) ⇒ Q.MatrixPasses the suppliedhtmlargument to thefromHtmlstatic method, then usescopy$to copy that result in to this instance.
Maths operations (non-destructive)
-
- add
Function( otherMatrix: Q.Matrix ) ⇒ Q.MatrixPasses this instance as the first argument andotherMatrixas the second argument to theaddstatic method and returns the result. -
- multiplyScalar
Function( scalar: Number ) ⇒ Q.MatrixPasses this instance as the first argument andotherMatrixas the second argument to themultiplyScalarstatic method and returns the result. -
- multiply
Function( otherMatrix: Q.Matrix ) ⇒ Q.MatrixPasses this instance as the first argument andotherMatrixas the second argument to themultiplystatic method and returns the result. -
- multiplyTensor
Function( otherMatrix: Q.Matrix ) ⇒ Q.MatrixPasses this instance as the first argument andotherMatrixas the second argument to themultiplyTensorstatic method and returns the result.
Maths operations (destructive)
-
- add$
Function( otherMatrix: Q.Matrix ) ⇒ Q.MatrixCalls theaddinstance method withotherMatrixas an argument andcopiesthe result to this instance. -
- multiplyScalar$
Function( otherMatrix: Q.Matrix ) ⇒ Q.MatrixCalls themultiplyScalarinstance method withotherMatrixas an argument andcopiesthe result to this instance.