1

I have a numpy matrix A and I need a function that will count (A[i,j]/sum of all elements in i-th column) - A[i,j]/sum of all elements in j-th row and it for every element in A.

I've already tried to write something along the line of:

a = A.sum(axis=0) 
b = A.sum(axis=1) 

for i in A: 
    for j in i: 
        f = A[i,j]/a(i) - A[i,j]/b(j)
2
  • Could you say a little more about what you have tried? Commented May 19, 2015 at 12:03
  • yep, i tried to write smth like: a=A.sum(axis=0) b=A.sum(axis=1) for i in A: for j in i: f=A[i,j]/a(i) - A[i,j]/b(j) Commented May 19, 2015 at 12:05

2 Answers 2

2

You should probably look for a vectorized solution than looping through all elements

A/A.sum(axis=0)[np.newaxis,:] -  A/A.sum(axis=1)[:,np.newaxis]

Suppose

In [35]: A = np.random.rand(10,3)
Out[35]:
array([[ 0.26070074,  0.58940996,  0.78665012],
       [ 0.7420538 ,  0.72214655,  0.66633183],
       [ 0.67189673,  0.67298124,  0.04628626],
       [ 0.93935375,  0.45030544,  0.38292913],
       [ 0.45410731,  0.26557299,  0.09573014],
       [ 0.99872912,  0.31092656,  0.46294278],
       [ 0.61108329,  0.71140089,  0.85548017],
       [ 0.80012964,  0.64749927,  0.3292407 ],
       [ 0.33229818,  0.01810878,  0.44460486],
       [ 0.86525557,  0.0569463 ,  0.43183502]])

You could do the following.

In [36]: A*(1/A.sum(axis=0)[np.newaxis,:] -  1/A.sum(axis=1)[:,np.newaxis])
Out[36]:
array([[-0.12022572, -0.22751579, -0.3058817 ],
       [-0.23713606, -0.17649948, -0.16474676],
       [-0.3823249 , -0.33236228, -0.0229904 ],
       [-0.38921906, -0.1527391 , -0.13097127],
       [-0.48888156, -0.26594996, -0.09613741],
       [-0.41381789, -0.10546217, -0.15833642],
       [-0.18903571, -0.16660122, -0.20276794],
       [-0.33044427, -0.21874513, -0.11216096],
       [-0.36820095, -0.01870431, -0.46048657],
       [-0.5094047 , -0.02924623, -0.22300407]])
Sign up to request clarification or add additional context in comments.

Comments

0

I hope this could help:

def f(i,j,A):
    return A[i,j] * ( 1. / np.sum(A[i,])  ) -  ( 1. / np.sum(A[:,j])  )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.