Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute values in vector with NumPy

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
like image 562
Jamgreen Avatar asked Apr 26 '15 15:04

Jamgreen


People also ask

How do I sum all elements in a NumPy array?

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.

How do you sum a vector in Python?

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.

How do you find the magnitude of a vector in NumPy?

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.


1 Answers

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)
like image 76
jwilner Avatar answered Oct 03 '22 04:10

jwilner