1

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 x b 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.

1 Answer 1

4

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]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.