Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide ndarray by scalar - Numpy / Python

I'm just wondering how could I do such thing without using loops.

I made a simple test trying to call a division as we do with a numpy.array, but I got the same ndarray.

N = 2
M = 3

matrix_a = np.array([[15., 27., 360.],
            [180., 265., 79.]])
matrix_b = np.array([[.5, 1., .3], 
            [.25, .7, .4]])

matrix_c = np.zeros((N, M), float)

n_size = 360./N
m_size = 1./M

for i in range(N):
    for j in range(M):
        n = int(matrix_a[i][j] / n_size) % N
        m = int(matrix_b[i][j] / m_size) % M
        matrix_c[n][m] += 1 

matrix_c / (N * M)
print matrix_c  

I guess this should be pretty simple. Any help would be appreciated.

like image 573
pceccon Avatar asked Feb 15 '14 12:02

pceccon


People also ask

How do you divide every element in a NumPy array by scalar?

divide(arr1, arr2, out = None, where = True, casting = 'same_kind', order = 'K', dtype = None) : Array element from first array is divided by elements from second element (all happens element-wise). Both arr1 and arr2 must have same shape and element in arr2 must not be zero; otherwise it will raise an error.

How do I divide all values in a NumPy array?

Dividing a NumPy array by a constant is as easy as dividing two numbers. To divide each and every element of an array by a constant, use division arithmetic operator / . Pass array and constant as operands to the division operator as shown below. where a is input array and c is a constant.

Can you divide arrays Python?

Python's numpy. divide() computes the element-wise division of array elements. The elements in the first array are divided by the elements in the second array.


2 Answers

I think that you want to modify matrix_c in-place:

matrix_c /= (N * M)

Or probably less effective:

matrix_c = matrix_c / (N * M) 

Expression matrix_c / (N * M) doesn't change matrix_c - it creates a new matrix.

like image 132
Nigel Tufnel Avatar answered Oct 21 '22 14:10

Nigel Tufnel


Another solution would be to use numpy.divide

matric_c = np.divide(matrix_c, N*M)

Just make sure N*M is a float in case your looking for precision.

like image 21
Kenan Avatar answered Oct 21 '22 14:10

Kenan