Engineering/Mathematics/Matrices
Matrix Multiplication
The product is defined one column at a time: column of is the matrix-vector product of with column of . The definition forces the inner dimensions to agree, changes the result size, and yields an operation that is emphatically not commutative.
- Core level
- Stream: matrix-algebra
- Reading time 13 min
- Ref KVS-ENG-MATH-0039
- Taxonomy
- Engineering / Mathematics
- Prerequisite
- The matrix-vector product
- Conformability
- is , is — inner dimensions must match
- Result size
- — the outer dimensions
- Commutative?
- No. in general, and often only one is defined
- Cost
- floating-point operations for the direct algorithm
Overview
Matrix multiplication is the operation that makes matrix algebra more than a bookkeeping convenience, and it is defined by extending the matrix-vector product across the columns of a second matrix. If is and is with columns , then is the matrix whose -th column is . Each column of the result is an independent linear combination of the columns of , weighted by one column of .
Two features distinguish this from the operations defined earlier. It is not entrywise: the entry in position of depends on an entire row of and an entire column of , not on the entries in position of the operands. And it is not shape-preserving: the operands may have three different sizes between them, with the inner dimensions required to agree and the outer dimensions determining the result. An entrywise product of same-sized matrices is a perfectly definable operation, but it is not this one and does not have this one's properties.
The definition looks arbitrary until it is read as composition. Applying to a vector and then applying to the result is the same as applying the single matrix to that vector. Matrix multiplication is therefore the algebraic encoding of doing one linear operation after another, and the inner-dimension rule is simply the requirement that the output of the first stage be an acceptable input to the second. Every property the product has — associativity, distributivity, the failure of commutativity — is a property of composition.
The failure of commutativity is the point at which intuition carried over from scalar arithmetic must be abandoned. For rectangular matrices, reversing the order usually produces an undefined expression or a differently sized result. Even for square matrices of the same size, where both products exist and have the same shape, they generally differ. Nothing may be assumed about matrix products without a theorem, and the theorems that hold are the subject of a separate treatment.
Definition
Matrix Multiplication
MMLet be an matrix and an matrix with columns . The matrix product is the matrix whose -th column is the matrix-vector product . Symbolically, .
The product is written by juxtaposition. The number of columns of must equal the number of rows of ; no other pairing is defined.
Conformability for Multiplication
CFMTwo matrices are conformable for the product when the column count of equals the row count of . This shared value is the inner dimension and vanishes from the result; the surviving outer dimensions give the size of . Writing the sizes adjacently, , makes the rule mechanical.
Conformability for says nothing about conformability for . Both hold only when .
Commuting Matrices
CMMSquare matrices and of the same size commute when . This is a special property, not a general one. Examples include any matrix with the identity, any matrix with a scalar multiple of itself, any two powers of the same matrix, and any two diagonal matrices; generic pairs do not commute.
The commutator measures the failure and is central in control theory and quantum mechanics, where a non-zero commutator has direct physical meaning.
Concepts
Why the definition is what it is
Read and as linear operations. Applying to a vector and then applying gives , and the composite is itself a linear operation, so it must be represented by some matrix with for all . Setting extracts column of on the left and gives on the right, so must be exactly the matrix defined above. The definition is not a convention chosen for convenience; it is forced by the requirement that the product represent composition.
The size rule and what it means
The requirement that the inner dimensions agree is the requirement that the output of be an acceptable input to . If maps size- vectors to size- vectors and maps size- vectors to size- vectors, the composite maps size- to size-, which is precisely the shape of . Checking conformability is therefore not a formality but a check that the operations can be chained at all.
Non-commutativity, in three degrees
The failure of commutativity appears at three levels. For a general rectangular pair, is simply undefined: if is and is then is while requires a to match a . When both products exist but the matrices are not square, the results have different sizes: of size and of size give a product one way and a product the other. And when both are square of the same size, both products exist with the same shape but generally differ entry for entry.
Reading the product by columns and by rows
The definition says each column of is a combination of the columns of , with weights from the corresponding column of . It follows that every column of lies in the column space of , hence and . A symmetric argument on rows gives every row of as a combination of the rows of , so as well. Both bounds fall straight out of the column definition and are not obvious from an entrywise formula.
Zero divisors and the loss of cancellation
The product of two non-zero matrices can be the zero matrix — take with a single in position and with a single in position , both . Consequently does not imply , and does not imply that or is zero. Cancellation, taken for granted in scalar algebra, requires a hypothesis such as non-singularity of . Assuming it without that hypothesis is one of the most damaging errors in matrix manipulation.
Powers and the meaning of repetition
For a square matrix, denotes repeated products, which represents applying the same linear operation times. In a discrete-time state model , the state after steps is , so the long-run behaviour of the system is the behaviour of the powers — growth, decay or oscillation according to the eigenvalues. Powers are also where non-commutativity bites hardest: cannot be simplified to unless and commute.
Procedure: forming the product
Equations
Definition of the matrix product
EQ-MM-01Each column of the result is the matrix-vector product of with the corresponding column of .
Conformability and result size
EQ-MM-02The inner dimensions must agree and are consumed; the outer dimensions survive as the shape of the product.
The product as composition
EQ-MM-03Applying then equals applying . This property forces the definition rather than following from it as an afterthought.
Worked product of a with a
EQ-MM-04The result is . The reversed product does not exist, since a matrix cannot multiply a one.
Matrix multiplication is not commutative
EQ-MM-05Both products exist and are , yet they disagree in every entry. Order is part of the operation.
Rank bounds from the column and row readings
EQ-MM-06Every column of the product is a combination of the columns of , and every row is a combination of the rows of . Multiplication can destroy rank but never create it.
Zero divisors: non-zero matrices with zero product
EQ-MM-07Neither factor is the zero matrix, yet the product is. Cancellation therefore fails without a non-singularity hypothesis.
Variable Definitions
| Symbol | Name | Meaning | Domain / type |
|---|---|---|---|
| Left factor | The matrix whose columns are combined | M_{mn} | |
| Right factor | The matrix supplying the combination coefficients | M_{np} | |
| Column of | The -th column, a vector of size | C^n | |
| Matrix product | The matrix with -th column | M_{mp} | |
| Rows of | Becomes the row count of the product | positive integer | |
| Inner dimension | Columns of and rows of ; consumed by the product | positive integer | |
| Columns of | Becomes the column count of the product | positive integer | |
| Matrix power | The square matrix multiplied by itself times | n x n matrix | |
| Column space | Span of the columns of ; contains every column of | subspace of C^m |
Worked Numerical Example
Problem statement
A signal chain applies a mixing matrix to a three-channel intermediate signal, which is itself produced from two source presets by a matrix . Form the single equivalent matrix that maps presets directly to outputs, then demonstrate on a square pair that the order of multiplication cannot be reversed.
State the two matrices and check conformability
is and is . The inner dimensions are both , so exists and is . The reversed product would need a to match a and does not exist at all.
Compute the first column of the product
Column 1 of is with : combine the columns of with those weights. This gives .
Compute the second column
Column 2 uses . The zero coefficient drops the middle column of entirely: .
Assemble the product
Place the two computed columns side by side. The result is , mapping the two presets directly to three outputs and eliminating the intermediate stage.
Verify one entry independently
Compute as the weighted sum of row 3 of against column 2 of : . This matches, and because it traverses the data differently it is a genuine check on the column computation.
Confirm the composition property
Apply to the preset vector to get the intermediate , then apply to obtain . Applying the single matrix to gives . The two routes agree, as composition requires.
Demonstrate non-commutativity on a square pair
Take two matrices so that both orders are defined and both results are . Computing each entry from the row-column rule gives two entirely different matrices, so the order of a matrix product carries real information.
The single matrix replaces the two-stage chain exactly, so the intermediate signal need never be formed at runtime — a saving of one full pass over the data per sample, paid for once at configuration time. The square example shows why the order in which stages are collapsed cannot be permuted: swapping the two matrices changes every output. In a signal chain this is the formal statement that filtering then mixing is a different system from mixing then filtering.
Applications & Industry Use
Collapsing a transformation chain
Model, view and projection transformations are applied in sequence to every vertex. Multiplying the three matrices once per frame and applying the single result to millions of vertices replaces three matrix-vector products per vertex with one. The order of the product is fixed by the order of the transformations and cannot be permuted.
Forward kinematics by chained frames
The pose of an end effector is the product of homogeneous transformation matrices, one per joint, taken in link order. Non-commutativity is physically visible: rotating about one axis then another does not place the tool where the reverse order would.
State transition over multiple steps
For a discrete-time model , the state after samples is . Stability, settling and oscillation are read from the behaviour of the powers, and controllability matrices are built from products .
Batched layer evaluation
Evaluating a dense layer on a batch of samples is a matrix-matrix product rather than many matrix-vector products. This reuses each weight across the whole batch, moving the workload from memory-bound to compute-bound and delivering most of the throughput advantage of accelerator hardware.
Assembling element stiffness in global coordinates
An element stiffness matrix expressed in local coordinates becomes in global coordinates, a triple product with the rotation matrix . The order is dictated by which frame each factor acts in, and reversing it silently produces a wrong but plausible stiffness.
Multi-stage transition and flow models
A Markov chain's -step transition probabilities are the entries of . Similarly, chaining a supply matrix with a demand allocation matrix gives end-to-end flow in one operation, with the inner dimension being the intermediate stage that the product eliminates.
Design Considerations
Choose the multiplication order to minimise work
Associativity permits regrouping a chain of products, and the cost depends dramatically on the grouping. For of size , of size and of size , computing costs about operations while costs about million. Always contract against the vector first, and for longer chains solve the matrix chain ordering problem before executing.
Never form a product you only apply
If a chain of matrices is applied to a handful of vectors, apply the factors in turn rather than materialising the product. Forming costs operations and storage, both of which are wasted when the composite is used once. Materialise only when the composite will be reused many times or when a factorisation of it is required.
Treat order as semantically load-bearing
Because the product is not commutative, the order in an expression records the order of physical operations. Reversing a factor pair in code produces a result of the correct shape and entirely wrong meaning, which no dimension check will catch. Encode the order in naming conventions and validate against a case where the two orders demonstrably differ.
Do not assume cancellation
From it does not follow that , and from it does not follow that either factor is zero. Cancellation requires to be non-singular, in which case multiplying by on the left justifies it. Any manipulation that divides through by a matrix must first establish invertibility, and must respect the side on which the inverse is applied.
Exploit structure before optimising the general kernel
A product involving a diagonal matrix is a row or column scaling costing , not . A triangular, banded, orthogonal or low-rank factor similarly admits a much cheaper product. Recognising that a matrix is a permutation, a rotation or a rank-one update converts a cubic operation into a linear or quadratic one, which dwarfs any gain from tuning the dense algorithm.
Understand where the cost actually goes
The direct algorithm costs operations while reading entries, so unlike matrix-vector work it has high arithmetic intensity and can approach hardware peak. Achieving that requires blocking for cache and registers, which is exactly what tuned xGEMM implementations do. A naive triple loop typically reaches a small percentage of peak, so calling the library is not merely convenient but a large factor in performance.
Standards & Codes
Notation, interchange and numerical standards that govern how this material is written down, stored and computed in production systems.
| Reference | Title | Relevance to this topic |
|---|---|---|
BLAS Level 3 | Basic Linear Algebra Subprograms, matrix-matrix operations | The xGEMM routine defines the reference interface, including transpose flags and the scaling parameters that make a single call; it is the kernel around which dense linear algebra performance is organised. |
ISO 80000-2 | Quantities and units — Part 2: Mathematics | Fixes juxtaposition as the notation for the matrix product and the row-then-column index convention that determines which dimension is the inner one. |
IEEE 754-2019 | IEEE Standard for Floating-Point Arithmetic | Governs the accumulation inside each entry of the product; the fused multiply-add operation defined here is what allows tuned kernels to halve the rounding error while doubling throughput. |
ISO/IEC 14882 | Programming languages — C++ | Constrains the reassociation of the accumulation a conforming compiler may perform, and specifies the parallel execution policies used to distribute a product across cores. |
ISO/IEC 40314 | Mathematical Markup Language (MathML) Version 3.0 | Encodes juxtaposed matrix products with an explicit invisible-times operator, so the distinction between a product and adjacent unrelated symbols survives into assistive technology. |
Material Selection
For a mathematical topic, "material" is the numeric representation: the scalar field, storage format and precision the computation is built from.
| Representation | Select when | Trade-off |
|---|---|---|
| Dense binary64 with blocked GEMM | General-purpose scientific computation where accuracy is the priority and matrices fit in memory. | Approaches hardware peak with a tuned kernel; 8 bytes per entry and operations set a hard limit around a few tens of thousands per dimension. |
| Dense binary32 or reduced precision | Deep learning inference and training, and graphics pipelines. | Two to eight times the throughput on accelerator hardware; error grows with the inner dimension, so mixed-precision accumulation in a wider format is standard practice. |
| Sparse times dense | One factor comes from a mesh, network or graph with few non-zeros per row. | Cost proportional to non-zeros rather than to ; the product generally suffers fill-in, and irregular access prevents the kernel from reaching peak. |
| Structured factors (diagonal, permutation, orthogonal) | One factor is a scaling, a reordering or a rotation. | Reduces the product to work with no floating-point error in the permutation case; requires the structure to be recognised and preserved rather than assembled into a dense array. |
| Low-rank factored form | A large operator is well approximated by rank , as in compressed models and hierarchical matrices. | Cost drops from to ; introduces an approximation error and complicates further algebraic manipulation. |
| Integer or fixed-point arithmetic | Combinatorial products such as adjacency powers, or quantised inference on embedded targets. | Exact for combinatorial work and very fast on quantised hardware; the accumulator must be wide enough for the inner dimension or results overflow silently. |
Manufacturing Notes
Implementation notes — how the result is actually produced by hand, by algorithm and by library, including cost and numerical behaviour.
Operation count and arithmetic intensity
The direct algorithm performs multiplications and additions, about operations, while reading entries and writing . For square matrices this is arithmetic against data, an intensity proportional to . That is why matrix multiplication, unlike matrix-vector work, can reach hardware peak — and why almost all dense linear algebra is reorganised to spend its time here.
Hand procedure
Work one column of at a time and use the column-combination form: the coefficients are read from a single column and stay in view, and each partial result is a full-height vector. Verify by recomputing two or three entries with the row-against-column rule, choosing entries in different rows and columns so that a systematic error cannot hide.
Blocking, and why the library beats a triple loop
A naive triple loop reuses each operand entry times from cache and typically achieves a few percent of peak. Tiling the computation so that sub-blocks of , and the accumulator reside in cache and registers raises reuse to the block size and recovers most of the peak. Tuned xGEMM implementations perform several levels of such blocking together with explicit vectorisation and prefetching.
Sub-cubic algorithms in practice
Strassen's method reduces the exponent from to about by trading one multiplication for several additions in a recursive block decomposition, and becomes competitive for square matrices of a few thousand and above. It is numerically less stable than the direct algorithm, with a weaker componentwise error bound, and is therefore used selectively. Algorithms with better asymptotic exponents have constants far too large for practical sizes.
Verification techniques
For large products, a full recomputation is unaffordable. Freivalds' method checks probabilistically by drawing a random vector and comparing against , costing per trial with an error probability halving each time. Cheap deterministic checks include comparing row sums, since applied to the all-ones vector must equal applied to the row sums of .
Failure Modes & Common Mistakes
| Failure mode / mistake | Impact | Root cause | Prevention & detection |
|---|---|---|---|
| Reversing the order of the factors | high | Assuming commutativity, or transcribing a composition in the order the operations are performed rather than the order they are written. | Remember that acts last in . Validate against a case where both orders are defined and demonstrably differ; a shape check alone will not catch this for square matrices. |
| Non-conformable product | high | The column count of the left factor does not match the row count of the right factor, often after an unintended transpose. | Write the sizes adjacently as and confirm the inner values agree before computing. If they do not, check whether the other order was intended. |
| Assuming the product is entrywise | high | Generalising from addition and scalar multiplication, so A * B is used where A @ B is meant. | Check the result shape and one entry: the matrix product entry depends on a whole row and a whole column, whereas the entrywise product depends only on position . |
| Cancelling a common factor | high | Deducing from without establishing that is non-singular. | Justify cancellation by explicitly multiplying by , and note the side: left-multiplying by cancels a left factor only. |
| Materialising a product that is applied once | medium | Forming and then computing instead of . | Contract against the vector first. For longer chains, choose the parenthesisation that minimises the total operation count before executing anything. |
| Assuming | medium | Carrying scalar exponent rules into a non-commutative setting. | Expand the power explicitly: , which equals only when and commute. Verify commutation before applying any such simplification. |
| Accumulator overflow in integer or fixed-point products | medium | Summing products in an accumulator no wider than the operands, so a long inner dimension overflows silently. | Size the accumulator for the worst-case sum over the inner dimension, or rescale the operands; quantised inference kernels use a wider accumulator precisely for this reason. |
| Naive triple loop on large matrices | low | Hand-written multiplication with no blocking, achieving a few percent of hardware peak. | Call a tuned xGEMM. The gap between a naive loop and a blocked implementation is typically one to two orders of magnitude and grows with matrix size. |
FAQs
Why is matrix multiplication not defined entrywise?
Because the entrywise product does not represent composition of linear operations. The defining requirement is that applying and then should be the same as applying a single matrix, and that requirement forces the column-combination definition uniquely. The entrywise (Hadamard) product is a legitimate operation with its own uses, but it does not compose transformations and lacks the associativity structure that makes matrix algebra useful.
When do two matrices commute?
Rarely, and only in identifiable situations: any matrix commutes with the identity, with scalar multiples of itself, and with its own powers; diagonal matrices commute with one another; and simultaneously diagonalisable matrices commute. For a generic pair of square matrices, and differ in most entries. The commutator quantifies the difference and has direct physical meaning in quantum mechanics and Lie theory.
Can be defined when is not?
Yes, and this is the usual situation for rectangular matrices. If is and is then is , but requires the column count of to match the row count of , which fails. Both products exist only when is and is , and even then they have different sizes unless .
Does mean one of the factors is zero?
No. Matrices form a ring with zero divisors, so two non-zero matrices can multiply to give the zero matrix. Structurally this happens exactly when the column space of lies inside the null space of . The consequence for algebraic manipulation is that cancellation is invalid without a non-singularity hypothesis.
How should I order a chain of matrix multiplications?
By operation count, which associativity leaves free to choose. Contracting against a vector first is almost always right, and for a chain of matrices the optimal parenthesisation is found by a short dynamic program on the dimensions. The difference between a good and a bad grouping can be several orders of magnitude for matrices with very different shapes.
Is a faster-than-cubic algorithm worth using?
Sometimes. Strassen's method reduces the exponent to about and becomes competitive for square matrices from roughly a few thousand upward, at the cost of a weaker error bound and extra working memory. Algorithms with better asymptotic exponents carry constants so large that they are of theoretical interest only. For most work, a well-blocked cubic kernel is the right choice.
Why does the same product cost so differently depending on how it is coded?
Because the operation has enough arithmetic per byte to be compute-bound, but only if the data is reused from cache and registers. A naive triple loop reuses almost nothing and stalls on memory; a blocked implementation reuses each loaded block many times and approaches hardware peak. The resulting gap is typically one to two orders of magnitude, which is why the tuned library kernel is worth calling.
References
- Beezer, R. A. A First Course in Linear Algebra, Version 0.70. University of Puget Sound, 2006. Section MM, Subsection MM, Definition MM. Licensed under the GNU Free Documentation License v1.2.
- ISO 80000-2:2019, Quantities and units — Part 2: Mathematics. International Organization for Standardization.
- Golub, G. H. and Van Loan, C. F. Matrix Computations, 4th edition. Johns Hopkins University Press, 2013.
- Strassen, V. Gaussian Elimination is Not Optimal. Numerische Mathematik, 13, 1969.
- Goto, K. and van de Geijn, R. A. Anatomy of High-Performance Matrix Multiplication. ACM Transactions on Mathematical Software, 34(3), 2008.
AI Suggested Questions
- Find two 3x3 matrices that commute but are not diagonal, and explain what structure makes them commute.
- Work through the matrix chain ordering problem for four matrices with dimensions 40x20, 20x300, 300x10 and 10x5.
- Show me two non-zero 3x3 matrices whose product is the zero matrix, and describe the subspace relationship that causes it.
- At what matrix size does Strassen's algorithm start to beat a blocked cubic kernel on typical hardware, and what accuracy do you give up?
- Explain why rotating about the x-axis then the y-axis differs from the reverse, using the matrix product to make the difference explicit.
- How does Freivalds' algorithm verify a matrix product in quadratic time, and what is the failure probability after five trials?
Related Calculators
Multiply two matrices with a conformability check and a column-by-column trace of the computation.
Commutator CalculatorCompute , and the commutator for square matrices, and report whether the pair commutes.
Matrix Chain Order OptimiserGiven a chain of matrix dimensions, return the parenthesisation minimising the total operation count.
