There are many (mathematically speaking, infinite) ways to get the matrices. Using 3x3 design as an example, the following is a simple way to obtain them for main effects and interactions.
First contruct common effect vectors for all the factors (A and B in this case):
A1 = [1 1 1] (number of elements corresponds to the number of levels for this factor)
B1 = [1 1 1]
Then differential effects for all the factors:
A2
=
[1 -1 0
0 1 -1]
B2
=
[1 -1 0
0 1 -1]
The main effects and interaction for A and B are the Kronecker products:
A main effect
A2 ⊗ B1 (⊗: Kronecker product in mathematical notation)
=
1 1 1 -1 -1 -1 0 0 0
0 0 0 1 1 1 -1 -1 -1
B main effect
A1 ⊗ B2
=
1 -1 0 1 -1 0 1 -1 0
0 1 -1 0 1 -1 0 1 -1
Interaction
A2 ⊗ B2
=
1 -1 0 -1 1 0 0 0 0
0 1 -1 0 -1 1 0 0 0
0 0 0 1 -1 0 -1 1 0
0 0 0 0 1 -1 0 -1 1
Gang