Skip to content Skip to sidebar Skip to footer

How To Fill A Matrix In Python Using Iteration Over Rows And Columns

So I have an array of 5 integers v and another of 10 integers v. I have a 5 by 10 matrix P that I would want to fill so that (P)ij = v[i] + u[j] I tried: P = np.empty((len(asset_g

Solution 1:

Broadcasting is what you want to do. Although for small arrays such as yours, it doesn't make a difference, it makes a significant difference with larger arrays:

>>>arr1 = np.arange(5)>>>arr2 = np.arange(10,20)>>>arr1[:,None] + arr2
array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
       [13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
       [14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])

Generally with numpy you want to avoid iteration over rows and columns and use vectorized/broadcasted operations. This is where speed improvements actually come from.

So, elaborating based on your comment:

Say P_ij is ith element of x raised to the 4th power minus jth element of y raised to 2nd power

In general, Python supports most arithmetical operations you would want in a vectorized way, using the usual Python operators:

>>> arr1[:, None]**4 - arr2**2
array([[-100, -121, -144, -169, -196, -225, -256, -289, -324, -361],
       [ -99, -120, -143, -168, -195, -224, -255, -288, -323, -360],
       [ -84, -105, -128, -153, -180, -209, -240, -273, -308, -345],
       [ -19,  -40,  -63,  -88, -115, -144, -175, -208, -243, -280],
       [ 156,  135,  112,   87,   60,   31,    0,  -33,  -68, -105]])

Post a Comment for "How To Fill A Matrix In Python Using Iteration Over Rows And Columns"