[Tutor] Need help with arrays

Matt Gregory matt.gregory at oregonstate.edu
Thu May 5 18:49:31 CEST 2011


On 5/4/2011 10:30 AM, Patrick P. wrote:
> Hello,
>
> I hope this is the right way to ask my question, if not, sorry to bother
> you. Maybe you can tell me who to ask.
> Ok so here is my code
>
> [snip]
>
> A = np.array([[m111,m121], [m211,m221]])
> B = np.array([[m112,m122], [m212,m222]])
> print(np.dot(A,B))
>
> Traceback (most recent call last):
> File "C:/Python26/helpfiletest.py", line 36, in <module>
> print(np.dot(A,B))
> ValueError: objects are not aligned
> -------------------------------------------------------------------------------------
> I get it why theres and error message, because it's trying to multiply a
> 2x2x100 array with another 2x2x100 array and doesn't know how to do that.
> What I actually want is 100 2x2 arrays and then mutliply them individually.
> Can anyone help me with that?

As Alan said, you'll likely get good help on the numpy listserv, but I 
think this might be what you want, although I'm not sure it's the 
tersest way to express it:

# Swap axes twice on A and B to make them (100, 2, 2)
A_new = np.swapaxes(np.swapaxes(A, 0, 2), 1, 2)
B_new = np.swapaxes(np.swapaxes(B, 0, 2), 1, 2)

# Multiply the 2x2 arrays together using list comprehension
C = np.array([np.dot(a, b) for a, b in zip(A_new, B_new)])
print C

I'm certain there is a more clever way (ie. some function within numpy) 
to do that last part.

matt



More information about the Tutor mailing list