Hadamard Product (Element-wise Op)
The Hadamard product multiplies matching entries and keeps the shape. Compare it with matrix multiplication, build a mask, and check NumPy's * and @.
You have two arrays of the same shape. You want each number in the first array multiplied by the number in the matching position of the second.
That operation is the Hadamard product, also called elementwise multiplication. It preserves the shape:
$$\begin{bmatrix}1&2\\3&4\end{bmatrix} \odot \begin{bmatrix}5&6\\7&8\end{bmatrix} =\begin{bmatrix}5&12\\21&32\end{bmatrix}$$
The ⊙ symbol says “match positions.” The top-right entry is 2 × 6 = 12. It does not mix numbers from other positions.
Compare it with matrix multiplication
Using the same two arrays, matrix multiplication combines rows with columns:
$$\begin{bmatrix}1&2\\3&4\end{bmatrix} \begin{bmatrix}5&6\\7&8\end{bmatrix} =\begin{bmatrix}19&22\\43&50\end{bmatrix}$$
Its top-right entry is 1 × 6 + 2 × 8 = 22. The shapes happen to match the first result, so checking shape alone would not catch confusing these operations.
Predict: To zero the second entry of [3, 7, 2] while preserving the others, what array would you multiply it by elementwise?
Inspect both in code
With NumPy installed, run:
For NumPy arrays, * is elementwise multiplication and @ is matrix multiplication. These meanings depend on the objects: ordinary Python lists do not support list-by-list elementwise multiplication. For example, [1, 2] * 2 repeats the list instead.
A fixed mask also controls which input changes reach the output. Keep our mask [1, 0, 1]: changing the middle input from 7 to 100 still leaves the middle output at zero. Changing the first input passes straight through. The zero masks that position regardless of its value.
Try one change: Replace the lower-right entry of b with zero. Before running the code again, predict which entries change in each result.
The NumPy multiply reference shows additional array examples. Start with equal shapes. Its broadcasting cases extend the rules to compatible unequal shapes; they do not change what happened in our matching-position example.
- The Hadamard product multiplies matching entries. For equally shaped arrays, the output keeps that shape.
- For NumPy arrays, a * b is elementwise multiplication; a @ b is matrix multiplication.
- Matrix multiplication mixes row and column entries. Equal output shapes do not mean the operations agree.
- A fixed mask [1, 0, 1] preserves the first and third entries and zeros the second.
- Ordinary Python lists follow different rules: [1, 2] * 2 repeats the list.