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

loop-free operations on two-dimensional numpy arrays

This may seem a silly question to the community, but I didn’t manage to find an answer online. Imagine one has a situation like this:

area_vector = np.zeros(np.shape(normal))
for i in range(len(area)):
    area_vector[i] = area[i] * normal[i]

normal is a N x 3 array and area a 1D array of size N. As we can see, the loop is essentially an operation over rows of two-dimensional numpy arrays (area_vector and normal).

Is it possible to perform the above calculation in just 1 line (i.e. avoiding the for loop and using numpy’s built-in methods as much as possible)?

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

Thanks a lot,

>Solution :

Yes

import numpy as np
N = np.random.randint(10, 100)
normal = np.random.random((N, 3))
pressure = np.random.random((N, 1))
area = np.random.random((N, 1))
area_vector = np.zeros(np.shape(normal))
for i in range(len(pressure)):
    area_vector[i] = area[i] * normal[i]

area_vector_alternative = area * normal
print((area_vector_alternative == area_vector).all())

prints

True
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