Elementwise Operations

An elementwise operation applies the same operation to matching positions.

The result is:

[11 22 33]

Each element is added to the corresponding element.

Scalars apply to every element

The scalar 10 is applied to every element.

Elementwise arithmetic

Runs locally with Python in your browser.

Ready to run.

Elementwise multiplication is not dot product

This is elementwise:

a * b

This is a dot product:

a @ b

They answer different questions. Elementwise multiplication keeps one value per position. A dot product sums paired products into one scalar.

Predict the shape

If a.shape and b.shape are both (3,), then a + b has shape (3,).

Elementwise operations usually preserve the input shape, unless broadcasting is involved. Broadcasting comes later in this chapter.

Exercise: Elementwise result

If a = np.array([1, 2, 3]), what does a * 2 produce?

Answer it first, then check.

Hint

Apply the multiplication separately to 1, 2, and 3.

Solution

The result is:

[2 4 6]

Multiplying an array by a scalar multiplies every element by that scalar.