0
0
NumPydata~30 mins

Broadcasting for distance matrices in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Broadcasting for Distance Matrices
📖 Scenario: Imagine you have a few cities with their coordinates on a map. You want to find the distance between every pair of cities. This helps in planning trips or deliveries.
🎯 Goal: You will create a program that calculates the distance matrix between cities using numpy broadcasting. This means you will find all distances without writing loops, making the code fast and simple.
📋 What You'll Learn
Use numpy arrays to store city coordinates
Use broadcasting to calculate pairwise distances
Calculate Euclidean distance between points
Output the full distance matrix
💡 Why This Matters
🌍 Real World
Calculating distance matrices is useful in mapping, delivery route planning, and clustering locations based on proximity.
💼 Career
Data scientists and analysts often use broadcasting to efficiently compute distance matrices for machine learning, geographic analysis, and optimization problems.
Progress0 / 4 steps
1
Create city coordinates array
Create a numpy array called cities with these exact coordinates: [0, 0], [3, 4], and [6, 8]. Each coordinate is a list of two numbers representing x and y positions.
NumPy
Need a hint?

Use np.array and pass a list of lists with the coordinates.

2
Prepare for broadcasting
Create two new variables: cities_expanded_1 by adding a new axis to cities at position 1 using np.newaxis, and cities_expanded_2 by adding a new axis to cities at position 0 using np.newaxis.
NumPy
Need a hint?

Use np.newaxis inside the square brackets to add a dimension.

3
Calculate the distance matrix using broadcasting
Create a variable called distances that calculates the Euclidean distance between each pair of cities using cities_expanded_1 and cities_expanded_2. Use the formula: square root of the sum of squared differences along the last axis.
NumPy
Need a hint?

Subtract the expanded arrays, square the result, sum over the last axis, then take the square root.

4
Print the distance matrix
Print the variable distances to display the full distance matrix between the cities.
NumPy
Need a hint?

Use print(distances) to show the matrix.