LoginSignup
0
0

列ベクトルと行ベクトルの積と1次元配列

Last updated at Posted at 2023-11-14

はじめに

Pythonで列ベクトルと行ベクトルの積を計算するとき、思っていた結果にならず少し考えてしまいましたので、備忘録として残します。

問題

以下のような行列を考えます。

import numpy as np

mtx1 = [[1, 2],
        [3, 4],
        [5, 6]]

mtx2 = [[1, 2, 3],
        [4, 5, 6]]

mtx1_np, mtx2_np = np.array(mtx1), np.array(mtx2)

mtx1_npの1列目とmtx2_npの1行目の積を取りたいのですが、私はまず次のようにしました。

mtx1_ex, mtx2_ex = mtx1_np[:, 0].T, mtx2_np[0, :]
np.dot(mtx1_ex, mtx2_ex)
# 22

3行3列の行列となってほしかったのですが、スカラー値となってしまいました。

解決法

ここで、積を取った配列の形状を確認します。

mtx1_ex.shape, mtx2_ex.shape
# (3,) (3,)

どうやら1次元の配列となってしまうようで、次のようにすると正しく計算できました。

mtx1_ex, mtx2_ex = [mtx1_np[:, 0]], [mtx2_np[0, :]]
mtx1_ex, mtx2_ex = np.array(mtx1_ex).T, np.array(mtx2_ex)

mtx1_ex.shape, mtx2_ex.shape
# (3, 1) (1, 3)

np.dot(mtx1_ex, mtx2_ex)
# [[ 1  2  3]
#  [ 3  6  9]
#  [ 5 10 15]]

大事なところをまとめておきます。

mtx1_ex, mtx2_ex = mtx1_np[:, 0]], mtx2_np[0, :] # 誤
mtx1_ex, mtx2_ex = [mtx1_np[:, 0]], [mtx2_np[0, :]] # 正

終わりに

言語を問わず、今回のように時々意図しない結果になることがあります。
手戻りが少なくなるように、丁寧に確認しながら進めたいですね。

読んでいただきありがとうございました。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0