#!/usr/bin/env python # coding: utf-8 # # Broadcasting operations # ## General principle # # If you have an $(m, n)$ matrix $A$ and apply operations like sub(-), add(+), mul(*) or div(/) by a vector $v$ the shape of $v$ will be grow vertically or horizontally like: # # $(1,n)$ -> $(m,n)$ # # $(m,1)$ -> $(m,n)$ # ## Examples # # # 1) First # # $v = [1,2,3,4], x = 100$ # # $v + x = $ vector + escalar # # Python turns the 100 into a vector with the same shape of $v$, like: # # $v = [1,2,3,4] + [100, 100, 100, 100]$ # # $v = [101, 102, 103, 104]$ # # # 2) Second # # $v_1 = [[1,2,3],[4,5,6]]$ + $v_2 = [100, 200, 300]$ # # $v_2$ will become like: $[[100, 200, 300], [100, 200, 300]]$ # # 3) Third # # $v_1 = [[1,2,3],[4,5,6]]$ + $v2 = [[100],[200]]$ # # $v_2$ will become like: $[[100, 100, 100], [200, 200, 200]]$ # # ## In practice # In[2]: import numpy as np; # In[43]: A = np.array( [[56.0, 0.0, 4.4, 68.0], [1.2, 104.0, 52.0, 8.0], [1.8, 135.0, 99.0, 0.9]] ) print(A) # In[45]: sum = A.sum(axis = 0) sum # In[47]: A/sum