Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132923 views
License: OTHER
Kernel: Python 3
import numpy as np
n = 4 m = 5
x = np.arange(n) y = np.arange(m) x, y
(array([0, 1, 2, 3]), array([0, 1, 2, 3, 4]))

Version in the book

X, Y = np.meshgrid(x, y, indexing='ij') X
array([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3]])
Y
array([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]])
np.hypot(X, Y)
array([[ 0. , 1. , 2. , 3. , 4. ], [ 1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], [ 2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], [ 3. , 3.16227766, 3.60555128, 4.24264069, 5. ]])

Using indices

X, Y = np.indices((n, m))
np.hypot(X, Y)
array([[ 0. , 1. , 2. , 3. , 4. ], [ 1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], [ 2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], [ 3. , 3.16227766, 3.60555128, 4.24264069, 5. ]])
np.hypot(*np.indices((n, m)))
array([[ 0. , 1. , 2. , 3. , 4. ], [ 1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], [ 2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], [ 3. , 3.16227766, 3.60555128, 4.24264069, 5. ]])

Using fromfunction

np.fromfunction(np.hypot, (n, m))
array([[ 0. , 1. , 2. , 3. , 4. ], [ 1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], [ 2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], [ 3. , 3.16227766, 3.60555128, 4.24264069, 5. ]])

Using broadcasting

X = x[:, None] Y = y[None, :] X
array([[0], [1], [2], [3]])
Y
array([[0, 1, 2, 3, 4]])
X + Y
array([[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]])
np.sqrt(X**2 + Y**2)
array([[ 0. , 1. , 2. , 3. , 4. ], [ 1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], [ 2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], [ 3. , 3.16227766, 3.60555128, 4.24264069, 5. ]])

Using outer product

np.hypot.outer(x, y)
array([[ 0. , 1. , 2. , 3. , 4. ], [ 1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], [ 2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], [ 3. , 3.16227766, 3.60555128, 4.24264069, 5. ]])