Advanced Array Creation in NumPy

Why advanced array creation?

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.

1. meshgrid()

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]]

2. diag()

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

3. tile()

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]]

4. repeat()

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]]

Practical applications

  • meshgrid: Surface plots, PDE simulations, interpolation grids.
  • diag: Construct diagonal matrices, extract diagonals for checks.
  • tile: Generate tiled images, periodic boundary conditions in physics.
  • repeat: Data augmentation, broadcasting prep, element-level duplication.

Practice Exercises

# 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.
Numpy ones() zeros() eye() full() arange() linspace()
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer