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)?
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