# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import numpy as np

# 一维向量
v = np.array([1, 2, 3, 4])
print('v: ', v)

# 二维向量
m = np.array([[1, 2], [3, 4]])
print('m: ', m)

# 显示维度
print('v.shape: ', v.shape)
print('m.shape: ', m.shape)

# 显示大小
print('v.size: ', v.size)
print('m.size: ', m.size)

# +
# 数组生成函数

# 固定步长
x = np.arange(1, 10, 1) # arguments: start, stop, step  
print('x:\n', x)

# 固定长度
y = np.linspace(-10, 10, 25)
print('y:\n', y)

z = np.logspace(0, 10, 10, base=np.e)
print('z:\n', z)

# +
# 生成随机矩阵

# uniform random numbers in [0,1]
np.random.rand(5, 5)

# standard normal distributed random numbers
np.random.randn(5, 5)

# +
# 对角阵
np.diag([1, 2, 3])

# 次对角阵
np.diag([1, 2, 3, 4], k = 1)

# 零矩阵
np.zeros([3,3])

# 一矩阵
np.ones([3,3])

# +
# 索引

print(m)
print(m[0, 0])
print(m[:,1])

# +
# 切片, 同list

a = np.arange(5)
a[::2] # parameters: start, end, step
# -

A = np.array([[n+m*10 for n in range(5)] for m in range(5)])
print(A)
print(A[1:3, 1:3])

x = np.arange(0, 10, 0.5)
x[x>3]
x[(x>3) & (x<5)]
np.where((x>3) & (x<5))

# +
a = np.repeat('abc',3)

a = np.array([[1, 2], [3, 4]])
np.repeat(a, 3)
np.tile(a, 3)


# +
# 使用矢量化函数

def Theta(x):
    if x>=0:
        return 1
    else:
        return 0

# 矢量化
Theta_vec = np.vectorize(Theta)

Theta_vec(np.array([-1, 0, -1, 1, 3]))

# +
# any 和 all 的用法

M = np.array([[1, 4], [9, 16]])

if (M > 5).any():
    print('At least one element in M is bigger than 5')
else:
    print('no element in M is larger than 5')
    
if (M > 5).all():
    print('All elements in M are bigger than 5')
else:
    print('Not all elements in M is larger than 5')    

StarcoderdataJupyterScriptsDedupFiltered