Runoob Tutorial ArchiveEnglish

Matrix Addition and Matrix Multiplication

Matrix Addition and Matrix Multiplication

After understanding vector operations, we upgrade to matrices. Matrix multiplication is key to understanding neural network forward propagation—the essence of a fully connected layer is matrix multiplication.

Matrix Addition: Adding corresponding elements

For two matrices of the same shape, add the elements at corresponding positions—it's as intuitive as vector addition.

Matrix Multiplication: Dot product of rows and columns

Matrix multiplication is not as simple as "multiplying corresponding positions." Why?

The deeper meaning of a matrix is "linear transformation"—it maps one vector to another vector.

The matrix multiplication AB geometrically means: first apply the B transformation, then apply the A transformation. Therefore, the operation rule for AB must reflect the mathematical structure of a "composite transformation," not simple element-wise multiplication.

For example: A represents "horizontal stretch by 2 times," and B represents "90° counter-clockwise rotation." AB represents "rotate then stretch"—which is completely different from BA (stretch then rotate), so matrix multiplication does not satisfy the commutative law.

The operation rule is:

Left matrix

Row i →

·

Right matrix

Column j ↓

=

Result

(i, j)

The dot product of the i-th row of the left matrix and the j-th column of the right matrix $\rightarrow$ the value at position (i, j) of the result matrix.

Dimension matching rule

( (m \times \color{#e74c3c}{n}) ;\times; (\color{#e74c3c}{n} \times p) = (m \times p) )

Number of columns of AMust equalThe number of rows of B. The two highlighted n must be equal.

The shape of the result = (number of rows of A, number of columns of B)

Matrix multiplicationDoes not satisfy the commutative law: AB ≠ BA (in general).

The dimensions might not match, making BA undefined—this is the easiest mistake for beginners.

The essence of matrix multiplication is the composition of linear transformations

Multiplying by matrix A → performs one transformation; then multiplying by matrix B → performs a second transformation.

Two transformations composed = one (BA) transformation. This is why matrix multiplication is defined this way.


Real-life example

**Convenience store revenue calculation

Sales matrix for three days (row=date, column=product):

Coke Chips Instant noodles
Monday 10 5 3
Tuesday 8 7 4
Wednesday 12 4 6

Price Matrix (Row=Product, Column=Store):

Store 1 Store 2
Coke 3 3.5
Chips 5 5.5
Instant noodles 4 4.0

Sales matrix (3x3) x Price matrix (3x2) = Revenue matrix (3x2).

Each cell of the result = total revenue on a certain day in a certain store.


Mathematical definition

Matrix addition

[ (\mathbf{A} + \mathbf{B}){ij} = a{ij} + b_{ij} ]

Prerequisite: A and B have the exact same shape.

Matrix multiplication

Let A be m×n and B be n×p, then C = AB is m×p:

[ c_{ij} = \sum_{k=1}^{n} a_{ik} b_{kj} ]


Python hands-on practice

Example

import

numpy

as

np

A_runoob

=

np.

array

(

[

[

10

,

5

,

3

]

,

[

8

,

7

,

4

]

,

[

12

,

4

,

6

]

]

)

price

=

np.

array

(

[

[

3

,

3.5

]

,

[

5

,

5.5

]

,

[

4

,

4.0

]

]

)

Matrix addition (same shape)

bonus

=

np.

array

(

[

[

1

,

0

,

1

]

,

[

0

,

1

,

0

]

,

[

1

,

1

,

0

]

]

)

total

=

A_runoob + bonus

print

(

"A + bonus:\n"

,

total

)

Matrix multiplication: (3x3) @ (3x2) = (3x2)

revenue

=

A_runoob

@

price

print

(

"\nRevenue matrix A @ price:\n"

,

revenue

)

print

(

"Shape:"

,

revenue.

shape

)

Manually verify position (0,0)

manual

=

A_runoob

[

0

,

0

]

*price

[

0

,

0

]

[

0

,

1

]

*price

[

1

,

0

]

[

0

,

2

]

*price

[

2

,

0

]

print

(

f

"\nManually verify [0,0]: {manual} == {revenue[0,0]}"

)

Dimension mismatch trap

print

(

f

"\nA shape: {A_runoob.shape}"

)

   

(3, 3)

print

(

f

"price.T shape: {price.T.shape}"

)

 

(2, 3)

A @ price.T → (3,3) @ (2,3) mismatch!

Correct: price.T @ A → (2,3) @ (3,3) = (2,3)

print

(

f

"price.T @ A shape: {(price.T @ A_runoob).shape}"

)

 

(2, 3)

Original prompt (Chinese, left untranslated)



收入矩阵 A @ price:

 [[67.  72. ]

 [75.  79.5]

 [80.  88. ]]

形状: (3, 2)



A 形状: (3, 3)

price.T 形状: (2, 3)

price.T @ A 形状: (2, 3)


Interactive Matrix Multiplication Visualization

Below demonstrates a 2x2 matrix A multiplied by a 2x1 vector v, observing how a linear transformation maps points on a circle to an ellipse:


Application scenarios in AI

Fully connected layer = Matrix multiplication

nn.Linear(d_in, d_out)The essence: weight matrix W (d_out × d_in) multiplied by input vector x (d_in dimensions) to get the output (d_out dimensions).

When processing batch data, the input X is a (batch, d_in) matrix, and the calculation is ( Y = XW^T ) or ( Y = WX^T ), which completes the forward pass for the entire batch in one matrix multiplication. GPUs have dedicated hardware acceleration for matrix multiplication (Tensor Core).

The QK^T of the attention mechanism

In Transformer, both Q and K are (seq_len, d_k) matrices. ( QK^T ) is seq_len×d_k multiplied by d_k×seq_len, resulting in an attention score matrix of (seq_len, seq_len).

In large models like GPT-4, seq_len can reach 128K, and the computation of this matrix multiplication accounts for a large portion of the entire inference cost. The FlashAttention algorithm is specifically designed to optimize the memory access pattern of this matrix multiplication.

Matrix multiplication implementation of convolution (im2col)

The convolution operation can be unfolded into a matrix multiplication: the input image is unfolded into a large matrix using a sliding window (im2col), and the convolution kernel is also flattened into a matrix, and the two are multiplied. This allows convolution to leverage highly optimized GEMM (General Matrix Multiplication) libraries for acceleration.

Matrix decomposition in LoRA fine-tuning

LoRA adds the product of two small matrices A and B next to the pre-trained weights: ( W' = W + AB ) . Here, AB is matrix multiplication—A is d×r, B is r×d, and the product is a low-rank matrix of d×d. One matrix multiplication achieves parameter-efficient fine-tuning.