Rotate a phone two ways in different order and it ends up facing differently
Turn a phone about one axis and then another, and it lands in one position; swap the order and it lands somewhere else. Rotation matrices, the grids of numbers that computers use to spin objects, capture that quirk exactly. On a flat plane, by contrast, the order of turns never matters.
In two dimensions a rotation matrix is a small square of four entries built from the cosine and sine of the turning angle. Write a point as a column of its two coordinates, multiply by the matrix, and out come the coordinates after rotating about the origin. The new horizontal position is x times the cosine minus y times the sine; the new vertical one is x times the sine plus y times the cosine. Those formulas are nothing but the angle-addition rules from trigonometry in disguise: turning a vector already at 30 degrees by another 45 simply places its tip at 75.
Rotations by quarter turns produce matrices filled only with zeros, ones and minus ones, and applying the quarter-turn matrix twice gives the negative of the identity, a half turn. Positive angles spin counterclockwise and negative ones clockwise, but conventions can flip that. Screen graphics usually put the origin in the top left with the vertical axis pointing down, which makes the same matrix turn things clockwise. Rotating the axes rather than the object also reverses the effect, and the fix is to use the inverse matrix, which for a rotation is simply its transpose.
That last fact is the formal definition. A rotation matrix is a square, real-valued matrix whose transpose equals its inverse and whose determinant is exactly one. A determinant of minus one would signal a reflection mixed in, sometimes called an improper rotation. All proper rotations of a given size form a group, the special orthogonal group, with the three-dimensional rotation group as the most familiar example.
The plane is the only interesting case where rotations commute. In three dimensions, as the phone shows, sequence changes the outcome, which is why graphics, physics and robotics software must track the order of every turn.
Source: Rotation matrix