How to avoid nested for loops in NumPy?

I have this code.

n_nodes = len(data_x)
X = np.zeros((n_nodes, n_nodes))

for i in range(n_nodes):
  for j in range(n_nodes):
    X[i, j] = data_x[i] ** j

I want to do the same task with no loops used at all. How can I do that with NumPy functions?

>Solution :

If data_x is big, you will be faster using only numpy functions.
You can first repeat the input array and then use np.power with a vector giving the powers. This should be calculated fully vectorised in comparison to the already given list comprehension version.

x = np.arange(10)
X = x[:,np.newaxis].repeat(x.size,axis=1)
X = np.power(X,np.arange(x.size))

If data_x is already a numpy array, you can use it directly, if not you would need to do

x = np.array(data_x)

Leave a Reply