Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading