I use NumPy.
I have defined a vector x
with NumPy and other variables with numerical values.
I will return a vector y
of same length as x
but the values y[i]
in this vector y
need to be computed from different formulas depending on the corresponding x[i]
.
Can I with NumPy do something smart or do I have to iterate through the vector x
and for each element in x
determine if x[i]
is either greater than or less than a specific value and determine which formula to use for the specific element?
I guess I could do something like
y[x > a] = 2*x+7
y[x <= a] = 3*x+9
return y
sum() in Python. The numpy. sum() function is available in the NumPy package of Python. This function is used to compute the sum of all elements, the sum of each row, and the sum of each column of a given array.
We can add vectors directly in Python by adding NumPy arrays. The example defines two vectors with three elements each, then adds them together. Running the example first prints the two parent vectors then prints a new vector that is the addition of the two vectors.
The numpy. dot() function calculates the dot-product between two different vectors, and the numpy. sqrt() function is used to calculate the square root of a particular number. We can calculate the dot-product of the vector with itself and then take the square root of the result to determine the magnitude of the vector.
Check out np.where
http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html.
y = np.where(x > a, 2 * x + 7, 3 * x + 9)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With