import numpy as np
#python lists
[1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
#numpy arrays/vectors
np.array([1,2,3])+np.array([4,5,6])
array([5, 7, 9])
# broadcast scalar to one dimensional array
a = np.array([1,2,3])
b = 2
c = a + b
print(a,"+",b,"=",c)
[1 2 3] + 2 = [3 4 5]
# broadcast scalar to two-dimensional array
A = np.array([
[1, 2, 3],
[1, 2, 3]])
b = 2
C = A + b
print(f"{A} + {b} = \n\n{C}")
[[1 2 3] [1 2 3]] + 2 = [[3 4 5] [3 4 5]]
# broadcast one-dimensional array to two-dimensional array
A = np.array([
[1, 2, 3],
[1, 2, 3]])
b = np.array([1, 2, 3])
C = A + b
print(A,"+",b,"=\n\n",C)
[[1 2 3] [1 2 3]] + [1 2 3] = [[2 4 6] [2 4 6]]
#vector addition
a = np.array([1, 2, 3])
b = np.array([1, 2, 3])
c = a + b
print(a,"+",b,"=",c)
[1 2 3] + [1 2 3] = [2 4 6]
#vector substraction
a = np.array([1, 2, 3])
b = np.array([.5, .5, .5])
c = a - b
print(a,"+",b,"=",c)
[1 2 3] + [0.5 0.5 0.5] = [0.5 1.5 2.5]
#vector multiplication
a = np.array([1, 2, 3])
b = np.array([1, 2, 3])
c = a * b
print(a,"*",b,"=",c)
[1 2 3] * [1 2 3] = [1 4 9]
#vector division
a = np.array([1, 2, 3])
b = np.array([1, 2, 3])
c = a / b
print(a,"/",b,"=",c)
[1 2 3] / [1 2 3] = [1. 1. 1.]
#vector dot product:
# a = [a1,a2,a3] b = [b1,b2,b3]
# a . b = (a1 x b1 + a2 x b2 + a3 x b3)
a = np.array([1, 2, 3])
b = np.array([1, 2, 3])
c = a.dot(b)
print(a," dot ",b,"=",c)
[1 2 3] dot [1 2 3] = 14
#vector-scalar multiplication
v = np.array([1, 2, 3])
s = 0.5
c = s * v
print(v," * ",s," = " ,c)
[1 2 3] * 0.5 = [0.5 1. 1.5]
#L1 norm: the sum of the absolute vector values
from numpy.linalg import norm
a = np.array([1, 2, 3])
#'1' specify the norm order
l1 = norm(a, 1)
print(l1)
6.0
#L2 norm: the square root of the sum of the squared vector values
a = np.array([1, 2, 3])
l2 = norm(a)
print(l2)
3.7416573867739413
# vector max norm
from math import inf
from numpy.linalg import norm
a = np.array([1, 2, 3])
maxnorm = norm(a, inf)
print(maxnorm)
3.0
#max = 10+1
norm([[2,3],[2,4],[10,1]],inf)
11.0