user27886
user27886

Reputation: 582

One liner for matrix-wise operations in python numpy (coming from MATLAB environment)

Each column of a matrix should sum to 1. In MATLAB I would write for a matrix mat

> mat = rand(5)

mat =
    0.2017    0.3976    0.0318    0.2750    0.2225
    0.0242    0.1222    0.1369    0.2883    0.3395
    0.0390    0.4260    0.2395    0.1462    0.2816
    0.0351    0.1851    0.2292    0.2386    0.3376
    0.1624    0.0157    0.2125    0.2813    0.2388

> mat = mat ./ ( ones(5,1) * sum(mat) )

mat = 
    0.4363    0.3467    0.0374    0.2237    0.1567
    0.0522    0.1066    0.1610    0.2345    0.2391
    0.0844    0.3715    0.2819    0.1189    0.1983
    0.0760    0.1614    0.2697    0.1941    0.2377
    0.3511    0.0137    0.2500    0.2288    0.1682

so that

> sum(mat)

ans = 
    1.0000    1.0000    1.0000    1.0000    1.0000

I hope this is an appropriate question for this site. Thanks.

Upvotes: 0

Views: 206

Answers (2)

Thibaut
Thibaut

Reputation: 1408

This operation can be written very concisely in numpy:

import numpy as np

mat = np.random.rand(5, 5)
mat /= mat.sum(0)
mat.sum(0) # will be array([ 1.,  1.,  1.,  1.,  1.])

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

In NumPy you can do this by performing almost exactly the same operations:

>>> import numpy as np
>>> mat = np.random.rand(5, 5)
>>> new_mat = mat / (np.ones((5, 1)) * sum(mat))
>>> new_mat.sum(axis=0)
array([ 1.,  1.,  1.,  1.,  1.])

Upvotes: 1

Related Questions