简体   繁体   中英

Python numpy function for matrix math

I have to np arrays

a = np.array[[1,2]
             [2,3]
             [3,4]
             [5,6]]

b = np.array [[2,4]
              [6,8]
              [10,11]

I want to multiple each row of a against each element in array b so that array c is created with dimensions of a-rows xb rows (as columns)

c = np.array[[2,8],[6,16],[10,22]
             [4,12],[12,21],[20,33]
             ....]

There are other options for doing this, but I would really like to leverage the speed of numpy's ufuncs...if possible.

any and all help is appreciated.

Does this do what you want?

>>> a
array([[1, 2],
       [2, 3],
       [3, 4],
       [5, 6]])

>>> b
array([[ 2,  4],
       [ 6,  8],
       [10, 11]])

>>> a[:,None,:]*b
array([[[ 2,  8],
        [ 6, 16],
        [10, 22]],

       [[ 4, 12],
        [12, 24],
        [20, 33]],

       [[ 6, 16],
        [18, 32],
        [30, 44]],

       [[10, 24],
        [30, 48],
        [50, 66]]])

>>> _.shape
(4, 3, 2)

Or if that doesn't have the right shape, you can reshape it:

>>> (a[:,None,:]*b).reshape((a.shape[0]*b.shape[0], 2))
array([[ 2,  8],
       [ 6, 16],
       [10, 22],
       [ 4, 12],
       [12, 24],
       [20, 33],
       [ 6, 16],
       [18, 32],
       [30, 44],
       [10, 24],
       [30, 48],
       [50, 66]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM