[Tutor] Python 3.6 Multiply the elements of a 2D Array by the elements of a 1D Aeeay

giacomo.boffi at gmail.com giacomo.boffi at gmail.com
Sun Apr 16 16:28:59 EDT 2017


"Stephen P. Molnar" <s.molnar at sbcglobal.net> writes:

> I have an list generated by:   s = np.linspace(start,finish,points)
>
> and an array D:
>
>  [ 0.          2.059801    3.60937686  3.32591826  2.81569212]
>  [ 2.059801    0.          4.71452879  4.45776445  4.00467382]
>  [ 3.60937686  4.71452879  0.          5.66500917  5.26602175]
>  [ 3.32591826  4.45776445  5.66500917  0.          5.02324896]
>  [ 2.81569212  4.00467382  5.26602175  5.02324896  0.        ]
>
> Now I can multiply the Array by one element of the list:
>
> s2 = 1.100334448160535050  (The first non-zero list element.)
> s2_D = s2*np.array(D)
>
> which results in:
>
>  [ 0.          2.26647     3.97152169  3.65962243  3.09820303]
>  [ 2.26647     0.          5.18755844  4.90503178  4.40648056]
>  [ 3.97152169  5.18755844  0.          6.23340474  5.79438514]
>  [ 3.65962243  4.90503178  6.23340474  0.          5.52725387]
>  [ 3.09820303  4.40648056  5.79438514  5.52725387  0.        ]
>
> I checked this, rather laboriously, in a spreadsheet.
>
> However, what I want to do is multiply each element ob D by each
> element of s and sum all of the products.

if I understand what you want to do,

  R_ij = sum_k(D_ij s_k)

you can do it in a number of ways, say D has shape(i, j) and s has shape(k)

Possibility 1

c = np.outer(D, s) # c has shape (i*j, k) as outer flattens its arguments 
c = sum(c, 1)      # c has shape (i*j) because se summed over 2nd index
c.reshape(D.shape) # c has the shape of D, i.e., (i, j)

Possibility 2

# https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html
stackoverflow.com/questions/26089893/understanding-numpys-einsum
c = np.einsum('ij,k -> ij', D, s)




More information about the Tutor mailing list