Arange
#arange
vec1 = np.arange(0,11)
print("vec1={}".format(vec1))
vec1 = np.arange(0,10, step=2)
print("vec1={}".format(vec1))
#results:
vec1=[ 0 1 2 3 4 5 6 7 8 9 10]
vec1=[0 2 4 6 8]
Linspace
#linspace
vec2 = np.linspace(0, 5, num=5)
print("vec2={}".format(vec2))
vec2 = np.linspace(0,5,num=5,endpoint=False)
print("vec2={}".format(vec2))
vec2 = np.linspace(0,5,num=10,endpoint=True)
print("vec2={}".format(vec2))
results:
vec2=[0. 1.25 2.5 3.75 5. ]
vec2=[0. 1. 2. 3. 4.]
vec2=[0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778
3.33333333 3.88888889 4.44444444 5. ]
Other methods
#ones,eye,empty, full,random
vec3 = np.ones((3,3))
print("vec3=""{}".format(vec3))
vec3 = np.empty((3,3))
print("vec3=""{}".format(vec3))
vec3 = np.full((3,2), 7)
print("vec3=""{}".format(vec3))
vec3 = np.eye(3) *9.9
print("vec3=""{}".format(vec3))
vec3 = np.random.random((4,5))
print("vec3=""{}".format(vec3))
results:
ad1. vec3=
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
ad.3 vec3=
[[7 7]
[7 7]
[7 7]]
ad.4 vec3=
[[9.9 0. 0. ]
[0. 9.9 0. ]
[0. 0. 9.9]]
ad.5 vec3=
[[0.04031738 0.43108875 0.50419445 0.21100702 0.28018735]
[0.83468929 0.68595346 0.1951048 0.64249235 0.4666575 ]
[0.41041352 0.26075428 0.72763207 0.53344999 0.96080089]
[0.0299817 0.25032282 0.1049782 0.7117831 0.42239281]]
Matrix from array compliations
#matrix
m = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print("m=""{}".format(m))
row1 = m[1, :]
row2 = m[:2, :]
print("row1=""{}".format(row1)) # Prints "[1,2,3,4]
print("row2=""{}".format(row2)) # Prints "[5,6,7,8]
print(np.array([m[0, 0], m[1, 1], m[2, 0]]))
results:
m=
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
row1=[5 6 7 8]
row2=[[1 2 3 4]
[5 6 7 8]]
[1 6 9]
m1 = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
m2 = np.array([1, 0, 1])
m = m1 + m2 # Add v to each row of x using broadcasting
print("m=""{}".format(m))
m=
[[ 2 2 4] #1+1, 2+0, 3+1
[ 5 5 7] #4+1,5+0,6+1
[ 8 8 10] #7+1,8+0,9+1
[11 11 13]] #10+1,11+0,12+1