2
\$\begingroup\$

I have written a function to multiply two numpy arrays.

def ra(self):
    """Multiply Rotation with initial Values"""
    rva = self.r_array() * self.va_array()
    rva = np.sum(rva, axis=1)  # Sum rows of Matrix
    rva = np.array([[rva[0]],  # Transpose Matrix
                    [rva[1]],
                    [rva[2]]])

where:

  • r_array has 3 rows and 3 columns
  • va_array has 3 rows and 1 column

I feel like this should be able to be written in one line. However, self.r_array() * self.va_array() always returns a 3 x 3 array.

Any suggestions would be greatly appreciated.

Cheers

\$\endgroup\$
4
  • \$\begingroup\$ stackoverflow.com/a/21563036 Use r_array.dot(va_array) or @ operator. \$\endgroup\$
    – aki
    Commented Jul 11, 2020 at 6:06
  • \$\begingroup\$ @Peilonrayz - Thank you for the welcome. My code did work as intended, hence why I posted it here and not at in Stack Overflow. I generated a workaround that produced the correct answer but was not elegant. The problem was that I did not know how to do this in one line. This was correctly answered below, however. \$\endgroup\$ Commented Jul 11, 2020 at 9:52
  • \$\begingroup\$ So it does, my apologies. \$\endgroup\$
    – Peilonrayz
    Commented Jul 11, 2020 at 9:59
  • \$\begingroup\$ Questions like this are common on SO. \$\endgroup\$
    – hpaulj
    Commented Jul 21, 2020 at 4:06

2 Answers 2

2
\$\begingroup\$

Actually the * operator does element-wise multiplication. So you need to use .dot() function to get the desired result.

Example :

import numpy as np

a = np.array([[1,2,3],
    [4,5,6],
    [7,8,9]])

b =  np.array([[1]
    ,[2],
    [3]])
print(a * b)
print(a.dot(b))

output :

[[ 1  2  3]
 [ 8 10 12]
 [21 24 27]]
[[14]
 [32]
 [50]]

Observe that when I have used * operator, every column in a is multiplied with b element-wise

\$\endgroup\$
3
  • 1
    \$\begingroup\$ @sai-sreenivas - Thank you for the answer. That worked to get it down to one line. It was working as intended before (unlike was suggesting and thus I dispute that it was off-topic) but this has made it significantly more elegant. \$\endgroup\$ Commented Jul 11, 2020 at 9:55
  • 2
    \$\begingroup\$ Why does this output different numbers to the OPs? OPs outputs 6, 30, 72 where yours outputs 14, 32, 50. \$\endgroup\$
    – Peilonrayz
    Commented Jul 11, 2020 at 9:59
  • 1
    \$\begingroup\$ May I know the reason for downvote? \$\endgroup\$
    – Sai
    Commented Jul 11, 2020 at 10:09
0
\$\begingroup\$

A one liner:

 np.sum(r_array*va_array, axis=1, keepdims=True)

To match r_array@va_array, use va_array.T in the 1liner.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.