Home > Back-end >  A more efficient way of creating an NxM array in Python
A more efficient way of creating an NxM array in Python

Time:11-15

In Python, I need to create an NxM matrix in which the ij entry has value of i^2 j^2.

I'm currently constructing it using two for loops, but the array is quite big and the computation time is long and I need to perform it several times. Is there a more efficient way of constructing such matrix using maybe Numpy ?

CodePudding user response:

You can use broadcasting in numpy. You may refer to the official documentation. For example,

import numpy as np
N = 3; M = 4   #whatever values you'd like

a = (np.arange(N)**2).reshape((-1,1))   #make it to column vector
b = np.arange(M)**2

print(a b)  #broadcasting applied

Instead of using np.arange(), you can use np.array([...some array...]) for customizing it.

  • Related