Matrix multiplication
Non-commutativity

An operation is commutative if, given two elements A and B such that the product A B {\displaystyle \mathbf {A} \mathbf {B} } is defined, then B A {\displaystyle \mathbf {B} \mathbf {A} } is also defined, and A B = B A. {\displaystyle \mathbf {A} \mathbf {B} =\mathbf {B} \mathbf {A}.}

If A and B are matrices of respective sizes m × n {\displaystyle m\times n} and p × q {\displaystyle p\times q}, then A B {\displaystyle \mathbf {A} \mathbf {B} } is defined if n = p {\displaystyle n=p}, and B A {\displaystyle \mathbf {B} \mathbf {A} } is defined if m = q {\displaystyle m=q}. Therefore, if one of the products is defined, the other one need not be defined. If m = q ≠ n = p {\displaystyle m=q\neq n=p}, the two products are defined, but have different sizes; thus they cannot be equal. Only if m = q = n = p {\displaystyle m=q=n=p}, that is, if A and B are square matrices of the same size, are both products defined and of the same size. Even in this case, one has in general

For example

but

This example may be expanded for showing that, if A is a n × n {\displaystyle n\times n} matrix with entries in a field F, then A B = B A {\displaystyle \mathbf {A} \mathbf {B} =\mathbf {B} \mathbf {A} } for every n × n {\displaystyle n\times n} matrix B with entries in F, if and only if A = c I {\displaystyle \mathbf {A} =c\,\mathbf {I} } where c ∈ F {\displaystyle c\in F}, and I is the n × n {\displaystyle n\times n} identity matrix. If, instead of a field, the entries are supposed to belong to a ring, then one must add the condition that c belongs to the center of the ring.

One special case where commutativity does occur is when D and E are two (square) diagonal matrices (of the same size); then DE = ED. Again, if the matrices are over a general ring rather than a field, the corresponding entries in each must also commute with each other for this to hold.
combination:repeat_prompt