Home > OS >  How can I manipulate a numpy array without nested loops?
How can I manipulate a numpy array without nested loops?

Time:02-23

If I have a MxN numpy array denoted arr, I wish to index over all elements and adjust the values like so

for m in range(arr.shape[0]):
    for n in range(arr.shape[1]):
        arr[m, n]  = x**2 * np.cos(m) * np.sin(n)

Where x is a random float.

Is there a way to broadcast this over the entire array without needing to loop? Thus, speeding up the run time.

CodePudding user response:

You are just adding zeros, because sin(2*pi*k) = 0 for integer k.

However, if you want to vectorize this, the function np.meshgrid could help you. Check the following example, where I removed the 2 pi in the trigonometric functions to add something unequal zero.

x = 2
arr = np.arange(12, dtype=float).reshape(4, 3)
n, m = np.meshgrid(np.arange(arr.shape[1]), np.arange(arr.shape[0]), sparse=True)
arr  = x**2 * np.cos(m) * np.sin(n)
arr

Edit: use the sparse argument to reduce memory consumption.

CodePudding user response:

You can use nested generators of two-dimensional arrays:

import numpy as np
from random import random

x = random()
n, m = 10,20
arr = [[x**2 * np.cos(2*np.pi*j) * np.sin(2*np.pi*i) for j in range(m)] for i in range(n)]
  • Related