piRSquared - 1 year ago 53

Python Question

consider array's

`a`

`b`

`a = np.array([`

[-1, 1, 5],

[-2, 3, 0]

])

b = np.array([

[1, 1, 0],

[0, 2, 3],

])

Looking at

`d = a.T.dot(b)`

d

array([[-1, -5, -6],

[ 1, 7, 9],

[ 5, 5, 0]])

`d[0, 0]`

`-1`

`a[:, 0] * b[:, 0]`

`[0, 0]`

`a[:, 0] * b[:, 0]`

with the above

`a`

`b`

`d = np.array([[a[:, i] * b[:, j] for j in range(a.shape[1])] for i in range(b.shape[1])])`

d

array([[[-1, 0],

[-1, -4],

[ 0, -6]],

[[ 1, 0],

[ 1, 6],

[ 0, 9]],

[[ 5, 0],

[ 5, 0],

[ 0, 0]]])

The sum of

`d`

`axis==2`

`a.T.dot(b)`

`d.sum(2)`

array([[-1, -5, -6],

[ 1, 7, 9],

[ 5, 5, 0]])

What is the most efficient way of getting

`d`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Here's one way:

```
In [219]: a
Out[219]:
array([[-1, 1, 5],
[-2, 3, 0]])
In [220]: b
Out[220]:
array([[1, 1, 0],
[0, 2, 3]])
In [221]: a.T[:,None,:] * b.T[None,:,:]
Out[221]:
array([[[-1, 0],
[-1, -4],
[ 0, -6]],
[[ 1, 0],
[ 1, 6],
[ 0, 9]],
[[ 5, 0],
[ 5, 0],
[ 0, 0]]])
```

Or...

```
In [231]: (a[:,None,:] * b[:,:,None]).T
Out[231]:
array([[[-1, 0],
[-1, -4],
[ 0, -6]],
[[ 1, 0],
[ 1, 6],
[ 0, 9]],
[[ 5, 0],
[ 5, 0],
[ 0, 0]]])
```