Jump to content

Matrix/Practice/Matrix multiplication: Difference between revisions

From Wikibase
AI-assisted (RonzzWikiCowriter) (via update-page on MediaWiki MCP Server)
AI-assisted (RonzzWikiCowriter) (via update-page on MediaWiki MCP Server)
Line 30: Line 30:
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}}
`np.dot` 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 ==

Revision as of 09:32, 19 November 2026

Languages: English · français · Esperanto

The solutions are programmatic: the code in each