0

I have two Nx3 matrices f and r, and I want to get this quantity

(f*r).sum()

Sometimes I need to change the sign of some of the columns of r before that calculation, for example

n=5
f=np.random.rand(n,3)
r=np.random.rand(n,3)

# real calculation
r[:, [0,2]]= -r[:, [0,2]]
got=(f*r).sum()

Is there any numpy trick to make this faster?

Edit:

maybe this?

got = (f * rr).sum(axis=0)
print(-got[0].sum() + got[1].sum() - got[2].sum())
nos
  • 19,875
  • 27
  • 98
  • 134
  • What kind of trick do you imagine there might be? Changing the sign of a column is no different from assigning a new value. I suppose you could multiply by `s=np.array([[-1,0,-1]])`. `f*r*s`. I don't know if that's any faster. – hpaulj Apr 25 '23 at 20:38
  • any kind of tricks – nos Apr 25 '23 at 21:12
  • `-r` is a multiplication`. I don't think anyone is claiming their suggestions **are** faster. That's for you to test on realistic size data. – hpaulj Apr 25 '23 at 21:36
  • I thought 1 bit is reserved for sign thus `-r` is a bit flip whereas `r*-1` is a real multiplication – nos Apr 26 '23 at 03:10
  • I did some time testing on (1000,3) shapes; and the differences are minor. You'll just have to do your testing. `-r` is faster that `-1*r`, but you are also indexing. Look at the whole picture, not just pieces. – hpaulj Apr 26 '23 at 04:07

2 Answers2

1

You can use the einsum function, which allows you to perform element-wise multiplication and summation of arrays using a single function call.

import numpy as np

n = 5
f = np.random.rand(n, 3)
r = np.random.rand(n, 3)

# Multiply f and r, changing the sign of columns 0 and 2 of r
result = np.einsum('ij,ij->i', f, np.array([-1, 1, -1]) * r)

print(result)

This should give you the same result as your original calculation, but it may be faster for large arrays. Note that the np.array([-1, 1, -1]) term changes the sign of columns 0 and 2 of r.

I recommend reading this answer for more details on how einsum works.

Sanskar Omar
  • 11
  • 1
  • 3
0

You can use multiplier list/array with respective multiplier for each column of r array:

(f * (r * [-1,1,-1])).sum()
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105