Python & Data Science
Deep Learning Under review

Matrix Multiplication Visually Why It S The Operat

1. Opening: The Rule That Feels Like Magic (and Not in a Good Way)

You’ve probably Googled “how to multiply matrices” more times than you’d like to admit. I know I have. The rule is easy to look up: take the dot product of each row of the first matrix with each column of the second. But that rule never feels right. It’s like memorizing a magic trick without understanding the sleight of hand.

Here’s the tension: the row-times-column rule is mechanically simple, but conceptually empty. You can compute AB, but you can’t explain what it means. And that’s a problem, because matrix multiplication is everywhere in data science — neural networks, covariance matrices, attention mechanisms. If you don’t have a mental picture, you’re just pushing numbers around.

This article is going to fix that. By the end, you’ll see matrix multiplication as composition of transformations — and the row-times-column rule will feel inevitable, not arbitrary. We’ll use a running example: a 90° rotation matrix and a horizontal shear matrix. We’ll compose them in both orders and watch what happens.

Let’s start with a quick refresher on what a single matrix does — then we’ll see what happens when we chain them.

2. Quick Recap: What a Single Matrix Actually Does

Before we compose two matrices, we need to be rock-solid on what one matrix does to a vector (and to the whole plane). The key insight: a matrix’s columns tell you where the basis vectors î and ĵ land. This isn’t a fact to memorize — it’s the definition of what the matrix is.

Let’s define two simple 2×2 matrices:

  • R = [[0, -1], [1, 0]] — a 90° counterclockwise rotation.
  • S = [[1, 1], [0, 1]] — a horizontal shear (pushes the top of a shape to the right).

For R, the first column [0, 1] means î (which starts at [1, 0]) lands at [0, 1]. The second column [-1, 0] means ĵ (which starts at [0, 1]) lands at [-1, 0]. So the whole plane rotates.

For S, the first column [1, 0] means î stays put. The second column [1, 1] means ĵ moves to [1, 1] — it gets a horizontal nudge.

Once you see a matrix as a set of landing spots for the basis vectors, you’ve already won half the battle. Let’s see this in code.

import numpy as np

# Define the rotation and shear matrices
R = np.array([[0, -1],
              [1,  0]])

S = np.array([[1, 1],
              [0, 1]])

# Corners of a unit square (as column vectors: each point is a column)
square = np.array([[0, 1, 1, 0],
                   [0, 0, 1, 1]])

# Apply each transformation to the square
rotated = R @ square
sheared = S @ square

print("Original square corners (x then y):")
print(square)
print("\nAfter rotation (R):")
print(rotated)
print("\nAfter shear (S):")
print(sheared)

What the output tells us:

  • The original square has corners at (0,0), (1,0), (1,1), (0,1).
  • After rotation, the square becomes a diamond: (0,0), (0,1), (-1,1), (-1,0). The shape is rotated 90° counterclockwise.
  • After shear, the square becomes a parallelogram: (0,0), (1,0), (2,1), (1,1). The top edge shifted right by 1 unit.

Now — what if we apply one transformation, and then another? That’s matrix multiplication.

3. The Core Idea: Composition = Following the Basis Vectors Twice

We have two matrices, A and B. We want a single matrix C that does the same thing as applying B, then A. How do we find C?

The visual approach: Take the basis vectors, apply B to them, then apply A to the result. The columns of C are simply where the basis vectors end up after this two-step journey.

Let’s work through it with our rotation R and shear S. We’ll compute C = R @ S (rotate after shear). Start with î = [1, 0]:

  • Apply S: S @ î = [1, 0] (î doesn’t move under shear).
  • Apply R to that: R @ [1, 0] = [0, 1].
  • So the first column of C is [0, 1].

Now ĵ = [0, 1]:

  • Apply S: S @ ĵ = [1, 1].
  • Apply R to that: R @ [1, 1] = [-1, 1].
  • So the second column of C is [-1, 1].

Therefore, C = [[0, -1], [1, 1]]. Let’s check that against the row-times-column rule.

import numpy as np

R = np.array([[0, -1],
              [1,  0]])
S = np.array([[1, 1],
              [0, 1]])

# Compute product using @ operator
C = R @ S
print("C = R @ S (rotate after shear):")
print(C)

# Now manually compute the first column by following basis vectors
# Start with basis vector i_hat = [1, 0]
i_hat = np.array([1, 0])
# Apply S first
step1 = S @ i_hat
print("\nAfter shear, i_hat lands at:", step1)
# Then apply R
step2 = R @ step1
print("After rotation, that point lands at:", step2)
print("This should match the first column of C:", C[:, 0])

# Repeat for j_hat = [0, 1]
j_hat = np.array([0, 1])
step1 = S @ j_hat
print("\nAfter shear, j_hat lands at:", step1)
step2 = R @ step1
print("After rotation, that point lands at:", step2)
print("This should match the second column of C:", C[:, 1])

What the output tells us: The manual following of basis vectors gives exactly the same columns as the @ operator. This is not a shortcut or a trick. This is what matrix multiplication means. The row-times-column rule is just a fast way to compute the same thing.

Each entry in the product matrix is a dot product — a measure of how much a row of the first matrix aligns with a column of the second. But the geometric story is simpler: follow the basis vectors twice.

4. The Hard Part: Why Order Matters (AB ≠ BA)

For numbers, 3×5 = 5×3. For matrices, AB is almost never equal to BA. This feels wrong at first — but geometrically, it’s obvious.

Let’s compute the product in the opposite order: D = S @ R (shear after rotation). We’ll compare D to C from before.

Before we run it, here’s the first entry of each product being dotted out — this is the whole “order matters” point in one calculation:

(RS)0,0=(0)(1)+(−1)(0)\term{a}{(RS)_{0,0}} = (0)(1) + (-1)(0)

Dot row 00 of RR with column 00 of SS.

0−0=0\term{a}{0 - 0} = 0

First entry of RSRS (rotate after shear).

(SR)0,0=(1)(0)+(1)(1)\term{b}{(SR)_{0,0}} = (1)(0) + (1)(1)

Dot row 00 of SS with column 00 of RR.

0+1=1\term{b}{0 + 1} = 1

First entry of SRSR (shear after rotation) — different, so order matters.

import numpy as np

R = np.array([[0, -1],
              [1,  0]])
S = np.array([[1, 1],
              [0, 1]])

# Two orders
C = R @ S  # rotate after shear
D = S @ R  # shear after rotation

print("R @ S (rotate after shear):")
print(C)
print("\nS @ R (shear after rotation):")
print(D)
print("\nAre they equal?", np.allclose(C, D))

# Apply each to the unit square
square = np.array([[0, 1, 1, 0],
                   [0, 0, 1, 1]])

transformed_C = C @ square
transformed_D = D @ square

print("\nSquare after R@S (rotate after shear):")
print(transformed_C)
print("\nSquare after S@R (shear after rotation):")
print(transformed_D)

What the output tells us: The two product matrices are completely different. When we rotate after shear, the square becomes a rotated parallelogram. When we shear after rotation, the square becomes a sheared rotated square — a different shape altogether.

Order matters because each transformation changes the space that the next one acts on. Doing things in a different order means the second transformation sees a different world. This is the hardest part of matrix multiplication, but the geometric view makes it feel natural — even if it still takes a moment to sink in.

5. So What Does That Mean for Us? (Data Science Applications)

You might be thinking: “Okay, I get the geometry, but how does this help me with real data?” Great question. Matrix multiplication is the engine behind many data science tools. Understanding it as composition demystifies why they work.

Neural network layers: Each layer is a matrix multiplication (plus bias and activation). Stacking layers is composing transformations. The first layer transforms the input space into a new representation; the next layer transforms that representation further. The order of layers matters enormously — just like our rotation and shear.

Covariance matrices: The covariance matrix Σ = X^T X / (n-1) is a matrix multiplication. Each entry is the dot product of two feature vectors — a measure of how they align. The composition view helps you see why the result is symmetric and positive semi-definite.

Attention mechanisms: In transformers, the QK^T multiplication is a composition of query and key spaces. The dot products measure alignment, just like in our basis-vector example.

You don’t need to memorize these applications now. The point is: every time you see a matrix multiplication in a data science context, you can ask yourself: what transformations are being composed?

Let’s check that against the data — with a small real-world example.

import numpy as np

# Synthetic dataset: 5 samples, 3 features
X = np.array([[2.0, 1.0, 0.0],
              [1.0, 3.0, 1.0],
              [0.0, 2.0, 2.0],
              [3.0, 1.0, 1.0],
              [1.0, 0.0, 3.0]])

# Center the data (subtract mean)
X_centered = X - X.mean(axis=0)

# Compute covariance matrix using matrix multiplication
n = X.shape[0]
cov = (X_centered.T @ X_centered) / (n - 1)

print("Covariance matrix (3x3):")
print(cov)

# Interpret a few entries
print("\nEntry (0,1) = {:.2f}: covariance between feature 0 and feature 1.".format(cov[0,1]))
print("Positive means they tend to increase together.")
print("Entry (0,2) = {:.2f}: covariance between feature 0 and feature 2.".format(cov[0,2]))
print("Close to zero means little linear relationship.")

What the output tells us: Each entry in the covariance matrix is a dot product between two centered feature vectors. The composition X^T X measures how each feature aligns with every other feature. This is exactly the same kind of dot product we used when following basis vectors — just with real data.

6. Wrapping Up: What You Actually Learned

Let’s recap the journey:

  1. Matrix multiplication is composition of transformations — follow the basis vectors twice. The columns of the product are where î and ĵ end up after both steps.
  2. The row-times-column rule is a fast way to compute this, not the meaning. It’s a consequence, not a definition.
  3. Order matters because each transformation changes the space for the next one. AB ≠ BA is obvious when you visualize it.

If the visual intuition still feels shaky, that’s normal. It takes a few passes. The key is to keep asking: where do the basis vectors go?

In the next article, we’ll look at the inverse of a matrix — which, visually, is just undoing a transformation.

Before you go, here’s a code block you can use to experiment with your own 2×2 matrices. Try composing different transformations and see what happens.

import numpy as np

# Experiment with your own matrices
def compose_and_visualize(A, B):
    """Print the product AB and the transformed unit square."""
    C = A @ B
    print("Product A @ B:")
    print(C)
    square = np.array([[0, 1, 1, 0],
                       [0, 0, 1, 1]])
    result = C @ square
    print("\nTransformed square corners:")
    print(result)

# Example: try a reflection matrix
reflect_x = np.array([[1, 0],
                      [0, -1]])
shear = np.array([[1, 1],
                  [0, 1]])

print("Reflection then shear:")
compose_and_visualize(shear, reflect_x)
print("\n---")
print("Shear then reflection:")
compose_and_visualize(reflect_x, shear)

Check Your Understanding

  • Remember: What are the columns of a matrix telling you? (Answer: where the basis vectors land.)
  • Understand: Explain in your own words why matrix multiplication is called “composition of transformations.”
  • Apply: Given matrices A and B, how would you find the first column of AB without using the row-times-column rule?
  • Analyze: Why does order matter for matrix multiplication but not for scalar multiplication? Use the geometric intuition.
  • Evaluate: In a neural network, why might swapping the order of two layers produce a completely different model?
  • Create: Design two 2×2 matrices that commute (AB = BA). What property must they have? (Hint: think about scaling and rotation.)

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans
  • Deep Learning Under review

    Batch Size And Learning Rate A Quick Reference Gui

    Let’s start with the rule you’ll see cited everywhere. In their 2017 paper “Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour,” Goyal et al.

  • Deep Learning Under review

    Reference: Optimizers

    A reference covering neural network optimizers from GD to AdamW, with learning-rate schedules, decision trees, and practical guidance for each architecture.

  • Deep Learning Under review

    Reference: Activation Functions

    A consolidated reference of activation functions—sigmoid, tanh, ReLU, GELU, softmax—with formulas, output ranges, gradient properties, and when to use each one.

  • Deep Learning Under review

    Borrowing Brains: A Beginner's Guide to Transfer Learning and Fine-Tuning

    Learn how transfer learning lets you borrow pretrained models like ResNet and BERT, swap their heads, freeze the body, and fine-tune for custom tasks.

Looking for something else?

Search every article by title, summary or topic.