MATLAB: dot(x1, x2, 2) > dot product > Numpy: 実装 v0.1, v0.2 > 一次元と二次元は確認

More than 1 year has passed since last update.

```GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 16.04 LTS desktop amd64
TensorFlow v1.2.1
cuDNN v5.1 for Linux
CUDA v8.0
Python 3.5.2
IPython 6.0.0 -- An enhanced Interactive Python.
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
scipy v0.19.1
geopandas v0.3.0
MATLAB R2017b (Home Edition)
```

MATLAB

```K>> x1 = [ 3 1 4; 1 5 9 ];
K>> x2 = [ 2 6 5; 3 5 8 ];
K>> res = dot(x1, x2, 2)

res =

32
100
```

Numpy 実装 v0.1

test_dotproduct_171123.py
```import numpy as np

# on Python 3.5.2

def calc_dotProduct_2d(x1, x2):
ndim = len(x1)
res = []
for idx in range(ndim):
res += [np.dot(x1[idx], x2[idx])]
return res

x1 = [[3, 1, 4], [1, 5, 9]]
x2 = [[2, 6, 5], [3, 5, 8]]

res = calc_dotProduct_2d(x1, x2)
print(res)

```
run
```\$ python3 test_dotproduct_171123.py
[32, 100]
```

３次元でも使えるかもしれないが、今は試さない。
１次元ではMATLABと答えが異なる。MATLABと合わせるにはnp.sum()が必要になる。

Numpy 実装 v0.2

１次元対応した。

test_dotproduct_171123.py
```import numpy as np

# on Python 3.5.2

def calc_dotProduct(x1, x2):
ndim = x1.ndim
if ndim == 1:
return np.sum(np.dot(x1, x2))

res = []
for idx in range(ndim):
res += [np.dot(x1[idx], x2[idx])]
return np.array(res)

def test_dotProduct_1d():
x1 = np.array([3, 1, 4])
x2 = np.array([2, 6, 5])
res = calc_dotProduct(x1, x2)
print(res)

def test_dotProduct_2d():
x1 = np.array([[3, 1, 4], [1, 5, 9]])
x2 = np.array([[2, 6, 5], [3, 5, 8]])
res = calc_dotProduct(x1, x2)
print(res)

test_dotProduct_1d()
test_dotProduct_2d()
```
run
```\$ python3 test_dotproduct_171123.py
32
[ 32 100]
```