1

I'm having a hard time on doing this. I have two m x n matrices (A and B) and I need to multiply every column of A by the rows in B, to generate a m x (n*n) matrix. I guess I wasn't very clear in the explanation so I'll post an example:

A = 
[1 2 
 3 4]
B = 
[5 6
 7 8]

I wish to have:

 [[5 6] [10 12]
  [21 24] [28 32]]

I was able to do it using for loops but I want to avoid for as much as possible. Also using numpy to all this and all data is stored as np.array.

2 Answers 2

3

Maybe:

>>> A = np.array([[1,2],[3,4]])
>>> B = np.array([[5,6],[7,8]])
>>> (A * B[None, :].T).T
array([[[ 5,  6],
        [21, 24]],

       [[10, 12],
        [28, 32]]])

where we use None to add an extra dimension to B, and a few transpositions to get the alignment right.

Sign up to request clarification or add additional context in comments.

3 Comments

@DSM, nice work. Is it convention to use None to increase the rank of the array?
@agconti: well, I think it's Officially Recommended(tm) to use np.newaxis as the name, but np.newaxis is simply another name for None. In principle though they could change it to another sentinel.
@DSM thanks! I've run into newaxis in the docs, but I never knew it was the same as None.
0

If I understand you right, you want basic ( m * n ) multiplication right? Use numpy.dot():

>>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.dot(a, b)
array([[4, 1],
       [2, 2]])

2 Comments

The expected output provided by the OP clearly suggests that basic multiplication is not what they need.
Actually no, and I don't know how to explain it clearly, so I believe the best thing to understand what I want is to look at the example

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.