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

Stephen P. Molnar s.molnar at sbcglobal.net
Mon Apr 17 06:21:03 EDT 2017


On 04/16/2017 04:57 PM, Sergio Rojas wrote:
>
> On 04/14/2017 04:21 AM, Peter Otten wrote:
>> Stephen P. Molnar wrote:
>>
>>> However, what I want to do is multiply each element ob D by each element
>>> of s and sum all of the products.
>>
>> If you *really* want this:
>>
>> sum_of_all_products = s.sum() * D.sum()
>>
>> example:
>>
>> s = [a b c]
>>
>> D = [[a1 a2]
>> [a3 a4]]
>>
>> a*a1 + a*a2 + a*a3 + a*a4 = a * D.sum()
>>
>> d := D.sum()
>> a*d + b*d + c*d = s.sum() * d
>>
>> Even if that's what you want you should heed Steven's advice.
>>
>
> Nice example on "analyze before computing". Nevertheless,
> A lazy man's approach to life might  go  using numpy ufunc.outer
>   [ https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.outer.html ]
>
>
> In [1]: import numpy as np
>
> In [2]: from sympy import symbols
>
> In [3]: x1, y1, z1, x2, y2, z2, x3, y3, z3 = symbols('x1 y1 z1 x2 y2 z2 x3 y3 z3
>     ...: ')
>
> In [4]: x=np.array([[x1,y1,z1], [x2,y2,z2], [x3,y3,z3]])
>
> In [5]: z=np.array([z1,z2,z3])
>
> In [6]: print(np.multiply.outer(z,x))
> [[[x1*z1 y1*z1 z1**2]
>    [x2*z1 y2*z1 z1*z2]
>    [x3*z1 y3*z1 z1*z3]]
>
>   [[x1*z2 y1*z2 z1*z2]
>    [x2*z2 y2*z2 z2**2]
>    [x3*z2 y3*z2 z2*z3]]
>
>   [[x1*z3 y1*z3 z1*z3]
>    [x2*z3 y2*z3 z2*z3]
>    [x3*z3 y3*z3 z3**2]]]
>
> In [7]: np.multiply.outer(z,x).sum()
> Out[7]: x1*z1 + x1*z2 + x1*z3 + x2*z1 + x2*z2 + x2*z3 + x3*z1 + x3*z2 + x3*z3 + y1*z1 + y1*z2 + y1*z3 + y2*z1 + y2*z2 + y2*z3 + y3*z1 + y3*z2 + y3*z3 + z1**2 + 2*z1*z2 + 2*z1*z3 + z2**2 + 2*z2*z3 + z3**2
>
> In [8]:
>
> Sergio
> https://www.packtpub.com/big-data-and-business-intelligence/numerical-and-scientific-computing-scipy-video
> https://github.com/rojassergio/Learning-Scipy
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

Thanks for the reply.

-- 
Stephen P. Molnar, Ph.D.		Life is a fuzzy set
www.molecular-modeling.net		Stochastic and multivariate
(614)312-7528 (c)
Skype: smolnar1


More information about the Tutor mailing list