[Numpy-discussion] Repeated dot products

josef.pktd@gmai... josef.pktd@gmai...
Sat Dec 12 16:17:03 CST 2009


On Sat, Dec 12, 2009 at 4:55 PM, T J <tjhnson@gmail.com> wrote:
> Hi,
>
> Suppose I have an array of shape:  (n, k, k).  In this case, I have n
> k-by-k matrices.  My goal is to compute the product of a (potentially
> large) user-specified selection (with replacement) of these matrices.
> For example,
>
>   x = [0,1,2,1,3,3,2,1,3,2,1,5,3,2,3,5,2,5,3,2,1,3,5,6]
>
> says that I want to take the 0th matrix and dot it with the 1st matrix
> and dot that product with the 2nd matrix and dot that product with the
> 1st matrix again and so on...
>
> Essentially, I am looking for efficient ways of doing this.  It seems
> like what I *need* is for dot to be a ufunc with a reduce() operator.
> Then I would construct an array of the matrices, as specified by the
> input x.  For now, I am using a python loop and this is unbearable.
>
>>>> prod = np.eye(k)
>>>> for i in x:
> ...  prod = dot(prod, matrices[i])
> ...
>
> Is there a better way?

I don't know about numpy, but I was using python reduce for similar:

>>> d = np.eye(2)
>>> li = [d,d,d,d,d,d,d,d]
>>> reduce(np.dot,li)
array([[ 1.,  0.],
       [ 0.,  1.]])

>>> lii = [1,2,1,2,3]
>>> reduce(lambda x,i : np.dot(x,li[i]),lii)
array([[ 1.,  0.],
       [ 0.,  1.]])

quickly written from memory, not sure its always correct, and no idea
about speed compared to loop

Josef

> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>


More information about the NumPy-Discussion mailing list