NumPy provides convenient functions for standard arrays like zeros, ones, and ranges. But in scientific computing, simulations, and matrix manipulations, we often need more advanced ways to construct arrays. Functions like meshgrid, diag, tile, and repeat help generate structured arrays for real-world tasks.
Generates coordinate matrices from coordinate vectors. Useful for 2D/3D plotting and simulations.
import numpy as np
x = np.array([1,2,3])
y = np.array([10,20,30])
X, Y = np.meshgrid(x, y)
print(X)
# [[1 2 3]
# [1 2 3]
# [1 2 3]]
print(Y)
# [[10 10 10]
# [20 20 20]
# [30 30 30]]
Extract or create diagonals of arrays. Common in linear algebra.
a = np.array([1,2,3,4])
print(np.diag(a))
# [[1 0 0 0]
# [0 2 0 0]
# [0 0 3 0]
# [0 0 0 4]]
M = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(np.diag(M)) # [1 5 9] extract diagonal
Repeat an array into a larger block. Handy for replicating patterns.
v = np.array([1,2,3])
print(np.tile(v, 3))
# [1 2 3 1 2 3 1 2 3]
M = np.array([[1,2],[3,4]])
print(np.tile(M, (2,3)))
# [[1 2 1 2 1 2]
# [3 4 3 4 3 4]
# [1 2 1 2 1 2]
# [3 4 3 4 3 4]]
Repeat elements of an array along a given axis.
x = np.array([1,2,3])
print(np.repeat(x, 2))
# [1 1 2 2 3 3]
M = np.array([[1,2],[3,4]])
print(np.repeat(M, 2, axis=0))
# [[1 2]
# [1 2]
# [3 4]
# [3 4]]
# 1) Create a grid of (x,y) points for x=[0,1,2] and y=[0,10,20,30].
# 2) Extract diagonal elements of a 4x4 matrix and replace them with zeros.
# 3) Tile [1,0] five times to create a 1D pattern.
# 4) Repeat each row of [[5,6],[7,8]] three times.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.