Python Numpy2 matrix

Create matrix from array of array

import numpy as np
# 3 x 2 matrix
mat1 = np.array([[1,2,3], [2,3,4]])
print(mat1)
#[[1 2 3]
# [2 3 4]]

Create 3 x 3 from reshape

reshape is useful to change structure of array

This is an example to make 3 x 3 from 1 dim array using arange

# 3 x 3 matrix
array1 = np.arange(9).reshape(3,3)
print(array1)

Get 1st row

array1 = np.arange(9).reshape(3,3)  # 0 - 8 3 x 3 matrix
# Get only 1 row
print(array1[0, :])  # [0 1 2]

Element base multiply

array1 = np.arange(9).reshape(3,3)        # 3 x 3
array2 = np.arange(9, 18).reshape(3, 3)   # 3 x 3
print(array1 * array2)  # multiply each element

Inner Product

array1 = np.arange(9).reshape(3,3)        # 3 x 3
array2 = np.arange(9, 18).reshape(3, 3)   # 3 x 3
print(np.dot(array1, array2))

Create Identity matrix

d = np.identity(4)
print(d)

'''
[[ 1.  0.  0.  0.]
 [ 0.  1.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]
'''

Create zero martix

a = np.zeros((3, 3))
print(a)

'''
[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]
'''

Create one matrix (all elements are one)

b = np.ones((3, 4))
print(b)

'''
[[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]
'''
Data Python
スポンサーリンク
Professional Programmer2

コメント