Module 3 · Section 3 of 11
Lesson 3.2 - Array Operations
Target: ~9 min read - 20 min hands-on
Overview
Slicing works like Python lists but extends to multiple dimensions (grid[1, :] for a
row, grid[:, 2] for a column). Broadcasting lets NumPy apply an operation between
arrays of different (but compatible) shapes without an explicit loop. We'll compute a
temperature profile along a cooling fin using this pattern.
Why This Matters (Engineering Context)
Broadcasting is what lets you apply one design equation across an entire array of operating conditions - every ambient case, every sensor channel, every candidate size - in a single line, instead of a loop per case.
Code-Along
import numpy as np
# [Mechanical/Chemical] steady-state temperature along a cooling fin
# T(x) = T_amb + (T_base - T_amb) * exp(-m x) (simplified long-fin form)
L = 0.10 # m, fin length
x = np.linspace(0, L, 13) # 13 evenly spaced positions from base (0) to tip (L)
T_base, T_amb, m = 120.0, 25.0, 45.0 # C, C, 1/m (fin parameter)
# np.exp works element-wise, so this one line gives temperature at ALL 13 points
T_x = T_amb + (T_base - T_amb) * np.exp(-m * x)
print("Position (mm):", np.round(x * 1000, 1)) # np.round rounds every element
print("Temp (C): ", np.round(T_x, 1))
# Slicing works like lists: [:3] first three, [-3:] last three
print("\nFirst 3 positions (m):", x[:3])
print("Last 3 temps (C):", np.round(T_x[-3:], 1))
# --- Broadcasting: combine a (3,1) column with a (1,13) row -> a (3,13) grid ---
# reshape(3, 1) makes a column vector; NumPy "stretches" it across the 13 columns
T_amb_cases = np.array([20.0, 25.0, 30.0]).reshape(3, 1)
T_grid = T_amb_cases + (T_base - T_amb_cases) * np.exp(-m * x).reshape(1, 13)
print("\nGrid shape:", T_grid.shape) # (3, 13): 3 cases x 13 positions
print("Fin-tip temp per ambient case (C):", np.round(T_grid[:, -1], 1)) # [:, -1] = last column
Run it: temperature is highest at the fin base (x = 0) and decays toward ambient
along the length. T_grid broadcasts the 3 ambient cases against the 13-position array
without a loop - its shape is (3, 13).
Practice Exercises
- Confirm the maximum of
T_xoccurs at the base (index 0) usingnp.argmax(). - Slice
T_gridto extract the row for the 30 C ambient case. - Build a (3, 13) grid instead by broadcasting an array of 3 different fin parameters
m = [30, 45, 60]againstx- what reshaping makes the broadcast work?
# Try the practice exercises here
Knowledge Check
- What does NumPy broadcasting allow you to do?
- Where is temperature highest along a fin losing heat to a cooler ambient?
- What NumPy function returns the index of the maximum value in an array?
Answer key
- Apply operations between arrays of different (but compatible) shapes without explicit loops
- At the base (where it meets the hot surface)
np.argmax()
25 / 63 sections · Course home · Join the coaching cohort