数学のブログ

Pythonと便利なライブラリたち 行列とその計算、NumPy、array、dot

Pythonで学ぶフーリエ解析と信号処理 (神永 正博)(著)、コロナ社)の第1章(Pythonと便利なライブラリたち)、章末問題1-5、6の解答を求めてみる。

コード(Python)

#!/usr/bin/env python3
import numpy as np

print('5.')

c = np.array([[1, 2],
              [3, 4],
              [5, 6]])

for o in [len(c) == 3, c.shape[0] == 3, c.shape[1] == 2]:
    print(o)

print('6.')

a = np.array([[1, 2, 3],
              [-1, 3, 5]])
b = np.array([[-2, 3],
              [1, -1],
              [2, -3]])
u = np.array([1, 2, 5]).reshape(3, 1)
c = np.dot(a, b)
v = a.dot(u)
v1 = np.dot(a, u)
for o in [c, v, v1]:
    print(o)
    print()

for _ in range(5):
    a = np.array(np.random.randint(-5, 5, 2 * 3)).reshape(2, 3)
    b = np.array(np.random.randint(-5, 5, 2 * 3)).reshape(3, 2)
    for o in [a, b, np.dot(a, b), a.dot(b)]:
        print(o)
        print()

入出力結果

% ./sample5.py 
5.
True
True
True
6.
[[  6  -8]
 [ 15 -21]]

[[20]
 [30]]

[[20]
 [30]]

[[ 0 -1 -5]
 [-4  3 -1]]

[[ 4  4]
 [-1  0]
 [ 3  1]]

[[-14  -5]
 [-22 -17]]

[[-14  -5]
 [-22 -17]]

[[-3  3  3]
 [-1  2 -4]]

[[-5  0]
 [-3 -4]
 [-1 -2]]

[[  3 -18]
 [  3   0]]

[[  3 -18]
 [  3   0]]

[[ 1 -4 -3]
 [-4 -2  3]]

[[-4  0]
 [ 2 -2]
 [ 1 -5]]

[[-15  23]
 [ 15 -11]]

[[-15  23]
 [ 15 -11]]

[[-2 -4 -2]
 [-4 -4 -2]]

[[-5  4]
 [ 1 -5]
 [-2 -2]]

[[10 16]
 [20  8]]

[[10 16]
 [20  8]]

[[ 4  3  4]
 [ 0 -5 -3]]

[[ 2  4]
 [ 1  4]
 [-3  4]]

[[ -1  44]
 [  4 -32]]

[[ -1  44]
 [  4 -32]]

%