Matrix/Practice/Matrix multiplication: Difference between revisions
AI-assisted (RonzzWikiCowriter) (via update-page on MediaWiki MCP Server) |
Automated edit (via update-page on MediaWiki MCP Server) |
||
| (10 intermediate revisions by 2 users not shown) | |||
| Line 1: | Line 1: | ||
Reference: [[Matrix#Matrix operations in python|Matrix operations in python]] | |||
The five exercises below come from a practical-work handout written for Matlab created by my beloved teacher [[Person:Gautier List|M. Gautier List]]<ref>{{#cite:Q3737}}</ref>, which we solve here with NumPy and SymPy. | |||
== Exercise 1 == | == Exercise 1 == | ||
| Line 30: | Line 32: | ||
M_1 = \begin{pmatrix} 0 & 0 & -1 \\ 2 & 1 & 0 \end{pmatrix}, \quad M_2 = \begin{pmatrix} 1 & 1 \\ 0 & -1 \\ -1 & 2 \end{pmatrix} | M_1 = \begin{pmatrix} 0 & 0 & -1 \\ 2 & 1 & 0 \end{pmatrix}, \quad M_2 = \begin{pmatrix} 1 & 1 \\ 0 & -1 \\ -1 & 2 \end{pmatrix} | ||
$$ | $$ | ||
{{Hidden solution}} | |||
<code>np.dot</code> gives the matrix product, not the element-wise one. The product exists only when the number of columns of $M_1$ equals the number of rows of $M_2$, which the code tests before multiplying. | |||
<syntaxhighlight lang="python" class="pyodide" copy> | |||
import numpy as np | |||
# the five pairs (M_1, M_2) | |||
pairs = [ | |||
([[1, 2], [3, 4]], [[5], [6]]), | |||
([[-2, 2, -3], [-1, 1, 3], [2, 0, -1]], [[2], [1], [-1]]), | |||
([[3, 4, 16], [45, 4, 0]], [[1], [2], [3]]), | |||
([[3, 2, 1, 2], [1, 4, 0, -1]], [[-3], [1], [2], [1]]), | |||
([[0, 0, -1], [2, 1, 0]], [[1, 1], [0, -1], [-1, 2]]), | |||
] | |||
for i, (M_1, M_2) in enumerate(pairs, start=1): | |||
M_1 = np.array(M_1) | |||
M_2 = np.array(M_2) | |||
compatible = M_1.shape[1] == M_2.shape[0] # columns of M_1 must equal rows of M_2 | |||
print(f"1.{i} M_1: {M_1.shape}, M_2: {M_2.shape}, product exists: {compatible}") | |||
if compatible: | |||
print(np.dot(M_1, M_2)) # matrix product, NOT np.multiply | |||
print() | |||
</syntaxhighlight> | |||
{{End hidden}} | |||
== Exercise 2 == | == Exercise 2 == | ||
| Line 53: | Line 82: | ||
4. $A^2 + AB + BA + B^2$ and $A^2 + 2AB + B^2$ with $A^2 = AA$. Conclude. | 4. $A^2 + AB + BA + B^2$ and $A^2 + 2AB + B^2$ with $A^2 = AA$. Conclude. | ||
{{Hidden solution}} | |||
SymPy keeps the arithmetic exact, so $A^{-1}$ shows $3/2$ instead of a rounded float. The comatrix follows from the reminder, $\operatorname{com}(A)=\det(A)A^{-1}$, and both expansions are compared with $(\mathbf A+\mathbf B)^2$. | |||
<syntaxhighlight lang="python" class="pyodide" copy> | |||
import sympy as sp | |||
A = sp.Matrix([[2, -2, 1], [-1, 0, 1], [0, 2, -2]]) | |||
B = sp.Matrix([[1, -1, 0], [-2, 0, 2], [0, 1, -1]]) | |||
def show(name, M): | |||
print(f"{name} =") | |||
for row in M.tolist(): | |||
print(" ", row) | |||
print() | |||
# 1. determinants and transposes | |||
print("det(A) =", A.det(), " det(B) =", B.det()) | |||
show("A^T", A.T) | |||
show("B^T", B.T) | |||
# 2. inverse, then comatrix through com(A) = det(A) A^-1 | |||
show("A^-1", A.inv()) | |||
show("com(A)", A.det() * A.inv()) | |||
# 3. products and sum | |||
show("A B", A * B) | |||
show("B A", B * A) | |||
show("A + B", A + B) | |||
# 4. the two expansions, with (A + B)^2 for comparison | |||
E_1 = A**2 + A * B + B * A + B**2 # A**2 is AA | |||
E_2 = A**2 + 2 * A * B + B**2 | |||
show("A^2 + AB + BA + B^2", E_1) | |||
show("A^2 + 2AB + B^2", E_2) | |||
show("(A + B)^2", (A + B)**2) | |||
print("A^2 + AB + BA + B^2 == (A + B)^2 :", E_1 == (A + B)**2) | |||
print("A^2 + 2AB + B^2 == (A + B)^2 :", E_2 == (A + B)**2) | |||
print("AB == BA :", A * B == B * A) | |||
</syntaxhighlight> | |||
{{End hidden}} | |||
== Exercise 3 == | == Exercise 3 == | ||
| Line 67: | Line 138: | ||
$$ | $$ | ||
using several methods. | using several methods. | ||
{{Hidden solution}} | |||
The scalar product is the sum of the element-wise products, which is also the $1\times3$ by $3\times1$ matrix product; the norm is the square root of a vector's scalar product with itself. | |||
<syntaxhighlight lang="python" class="pyodide" copy> | |||
import numpy as np | |||
u = np.array([7, 6, 3]) | |||
v = np.array([1, -1, 2]) | |||
w = np.array([2, 1, -1]) | |||
# 1. scalar product, three ways | |||
print("u . v, np.dot :", np.dot(u, v)) | |||
print("u . v, sum of products :", np.sum(u * v)) | |||
print("u . v, 1x3 times 3x1 :", (u.reshape(1, 3) @ v.reshape(3, 1)).item()) | |||
# 2. norm, three ways | |||
print("|w|, np.linalg.norm :", np.linalg.norm(w)) | |||
print("|w|, sqrt(w . w) :", np.sqrt(np.dot(w, w))) | |||
print("|w|, sqrt of square sum :", np.sqrt(np.sum(w ** 2))) | |||
</syntaxhighlight> | |||
{{End hidden}} | |||
== Exercise 4 == | == Exercise 4 == | ||
| Line 81: | Line 175: | ||
Put the problem in matrix form and determine the quantities of minerals $A$, $B$, and $C$ required to meet the specifications. | Put the problem in matrix form and determine the quantities of minerals $A$, $B$, and $C$ required to meet the specifications. | ||
{{Hidden solution}} | |||
With rows indexed by the constituents $a,b,c$ and columns by the minerals $A,B,C$, an entry is the amount of a constituent, in tonnes, per 1000 t of a mineral. Since $x,y,z$ are in thousands of tonnes, the demand is the matrix product itself: | |||
$$ | |||
\begin{pmatrix} | |||
600 & 700 & 700 \\ | |||
200 & 100 & 150 \\ | |||
100 & 150 & 50 | |||
\end{pmatrix} | |||
\begin{pmatrix} | |||
x \\ | |||
y \\ | |||
z | |||
\end{pmatrix} | |||
= | |||
\begin{pmatrix} | |||
20000 \\ | |||
5000 \\ | |||
3000 | |||
\end{pmatrix} | |||
$$ | |||
<syntaxhighlight lang="python" class="pyodide" copy> | |||
import sympy as sp | |||
# rows: constituents a, b, c ; columns: minerals A, B, C | |||
# entry (i, j) = tonnes of constituent i in 1000 t of mineral j | |||
G = sp.Matrix([[600, 700, 700], | |||
[200, 100, 150], | |||
[100, 150, 50]]) | |||
# monthly requirement, in tonnes | |||
d = sp.Matrix([20000, 5000, 3000]) | |||
print("det(G) =", G.det()) # non-zero, so the mineral mix is unique | |||
x = G.solve(d) # exact solution, in thousands of tonnes | |||
print("x, y, z (thousand t) =", x.T.tolist()) | |||
print("check G x =", (G * x).T.tolist()) | |||
print("in tonnes =", [float(c) * 1000 for c in x]) | |||
</syntaxhighlight> | |||
{{End hidden}} | |||
== Exercise 5 == | == Exercise 5 == | ||
| Line 97: | Line 234: | ||
3. $m = p \cdot q$ | 3. $m = p \cdot q$ | ||
{{Hidden solution}} | |||
The matrix of a linear map in the canonical basis has, as its $j$-th column, the image of the $j$-th basis vector, which is the Jacobian of the map with respect to $(x,y,z)$. Composing maps multiplies their matrices in the same order: $p=g\circ f$ has matrix $\mathbf G\mathbf F$, and $q=f\circ g$ has matrix $\mathbf F\mathbf G$. Each matrix is cross-checked against the direct symbolic composition. | |||
<syntaxhighlight lang="python" class="pyodide" copy> | |||
import sympy as sp | |||
x, y, z = sp.symbols("x y z") | |||
vec = sp.Matrix([x, y, z]) | |||
f = sp.Matrix([x + 3*z, x + y + 4*z, 3*x + 3*z]) | |||
g = sp.Matrix([x - z, y, -x + y]) | |||
# columns are the images of the basis vectors e_1, e_2, e_3 | |||
F = f.jacobian(vec) | |||
G = g.jacobian(vec) | |||
def compose(outer, inner): | |||
return outer.subs(list(zip(vec, list(inner))), simultaneous=True) | |||
# 1. p = g o f | |||
P = G * F | |||
print("P = G F =", P.tolist()) | |||
print("p(x, y, z) =", compose(g, f).T.tolist()) | |||
# 2. q = f o g | |||
Q = F * G | |||
print("Q = F G =", Q.tolist()) | |||
print("q(x, y, z) =", compose(f, g).T.tolist()) | |||
# 3. m = p . q | |||
M = P * Q | |||
print("M = P Q =", M.tolist()) | |||
print("m(x, y, z) =", compose(P * vec, Q * vec).T.tolist()) | |||
print("P Q == Q P :", P * Q == Q * P) | |||
</syntaxhighlight> | |||
{{End hidden}} | |||
== References == | |||
<references /> | |||
Latest revision as of 04:36, 20 November 2026
Reference: Matrix operations in python
The five exercises below come from a practical-work handout written for Matlab created by my beloved teacher M. Gautier List[1], which we solve here with NumPy and SymPy.
Exercise 1
Calculate (when it exists) the matrix product $M = M_1 M_2$ with:
1. $$ M_1 = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}, \quad M_2 = \begin{pmatrix} 5 \\ 6 \end{pmatrix} $$
2. $$ M_1 = \begin{pmatrix} -2 & 2 & -3 \\ -1 & 1 & 3 \\ 2 & 0 & -1 \end{pmatrix}, \quad M_2 = \begin{pmatrix} 2 \\ 1 \\ -1 \end{pmatrix} $$
3. $$ M_1 = \begin{pmatrix} 3 & 4 & 16 \\ 45 & 4 & 0 \end{pmatrix}, \quad M_2 = \begin{pmatrix} 1 \\ 2 \\ 3 \end{pmatrix} $$
4. $$ M_1 = \begin{pmatrix} 3 & 2 & 1 & 2 \\ 1 & 4 & 0 & -1 \end{pmatrix}, \quad M_2 = \begin{pmatrix} -3 \\ 1 \\ 2 \\ 1 \end{pmatrix} $$
5. $$ M_1 = \begin{pmatrix} 0 & 0 & -1 \\ 2 & 1 & 0 \end{pmatrix}, \quad M_2 = \begin{pmatrix} 1 & 1 \\ 0 & -1 \\ -1 & 2 \end{pmatrix} $$
Exercise 2
Let $A$ and $B$ be two square matrices:
$$ A = \begin{pmatrix} 2 & -2 & 1 \\ -1 & 0 & 1 \\ 0 & 2 & -2 \end{pmatrix}, \quad B = \begin{pmatrix} 1 & -1 & 0 \\ -2 & 0 & 2 \\ 0 & 1 & -1 \end{pmatrix} $$
Calculate the result of the following operations:
1. $\det(A)$, $\det(B)$, $A^T$, $B^T$.
2. $A^{-1}$. Deduce the comatrix of $A$.
Reminder: $$ A^{-1} = \frac{1}{\det(A)} \operatorname{com}(A) $$
3. $AB$, $BA$, and $A+B$.
4. $A^2 + AB + BA + B^2$ and $A^2 + 2AB + B^2$ with $A^2 = AA$. Conclude.
Exercise 3
1. Calculate the scalar product of the vectors $$ \vec{u} = \begin{pmatrix} 7 \\ 6 \\ 3 \end{pmatrix} \quad \text{and} \quad \vec{v} = \begin{pmatrix} 1 \\ -1 \\ 2 \end{pmatrix} $$ using several methods.
2. Calculate the norm of the vector $$ \vec{w} = \begin{pmatrix} 2 \\ 1 \\ -1 \end{pmatrix} $$ using several methods.
Exercise 4
A mining company operates three deposits and extracts three minerals $A$, $B$, and $C$, whose three main constituents $a$, $b$, and $c$ are identical, but whose grades vary such that:
- 1000 tonnes of $A$ contain 600 tonnes of $a$, 200 tonnes of $b$, and 100 tonnes of $c$.
- 1000 tonnes of $B$ contain 700 tonnes of $a$, 100 tonnes of $b$, and 150 tonnes of $c$.
- 1000 tonnes of $C$ contain 700 tonnes of $a$, 150 tonnes of $b$, and 50 tonnes of $c$.
The company must produce in one month 20000 tonnes of $a$, 5000 tonnes of $b$, and 3000 tonnes of $c$, and seeks the respective quantities of the three minerals it must extract.
Let $x$, $y$, and $z$ be the respective quantities of minerals $A$, $B$, and $C$ in thousands of tonnes that must be extracted.
Put the problem in matrix form and determine the quantities of minerals $A$, $B$, and $C$ required to meet the specifications.
Exercise 5
Let $f$ and $g$ be linear maps from $\mathbb{R}^3$ to $\mathbb{R}^3$ defined in the canonical bases by:
$$ f(x,y,z) = \begin{cases} x + 3z \\ x + y + 4z \\ 3x + 3z \end{cases}, \quad g(x,y,z) = \begin{cases} x - z \\ y \\ -x + y \end{cases} $$
Determine, in matrix form, the following linear maps (in the canonical bases):
1. $p = g \circ f$
2. $q = f \circ g$
3. $m = p \cdot q$