2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

簡単に試せるNumpyでの線形計算コード➁(初級編)

2
Posted at

「簡単に試せるNumpyでの線形計算コード➀(初級編)」
(Numpyの概要と行列の表示のさせ方と、行列の足し算に関して)
https://qiita.com/kenfukaya/items/fae288827976a8f79dc7

上記の記事の内容を踏まえ、Numpyで新たな計算をしていきます。

実際に線形計算をしてみた

・Numpyのインポート

import numpy as np

・形状の変更(6列→2行×3列)

入力

a = np.array([1,2,3,4,5,6])
b = a.reshape(2,3)

print('a =' , a)
print('b =' , b)

出力

a = [1 2 3 4 5 6]
b = [[1 2 3]
 [4 5 6]]

となり、a(6列)→b(2行×3列)に変更されていることを確認

・形状を確認

入力

b = ([[1,2,3],[4,5,6]])
b.shape

出力

(2,3)

2行×3列の形状を確認

・要素数を確認

入力

b = ([[1,2,3],[4,5,6]])
b.size

出力

6

要素数6となっていることを確認

・要素ごとの算術演算

入力

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

print('c =', c)

print('d =' ,d)

print('c+d =', c+d) #要素ごとの足し算

print('c-d =' , c-d ) #要素ごとの引き算

print('c*d =', c*d)   #要素ごとの掛け算

print('c/d =', c/d)  #要素ごとの割り算

出力

c = [[3 7 4]
 [2 8 5]
 [8 5 1]]

d = [[2 7 4]
 [4 9 4]
 [9 1 5]]

c+d = [[ 5 14  8]
 [ 6 17  9]
 [17  6  6]]

c-d = [[ 1  0  0]
 [-2 -1  1]
 [-1  4 -4]]

c*d = [[ 6 49 16]
 [ 8 72 20]
 [72  5  5]]

c/d = [[1.5        1.         1.        ]
 [0.5        0.88888889 1.25      ]
 [0.88888889 5.         0.2       ]]

・要素が全て0の行列を出力(ここでは3行×4列)

入力

x = np.zeros((3,4))
print('x = ', x)

出力

x =  [[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

・要素が全て1の行列を出力(ここでは2行×3列)

入力

y = np.ones((2,3))
print('y =',y)

出力

y = [[1. 1. 1.]
 [1. 1. 1.]]
2
0
0

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?