[Numpy-discussion] Apply transform to many small matrices
Jorge Scandaliaris
jorgesmbox-ml@yahoo...
Wed Feb 27 07:41:21 CST 2013
Jorge Scandaliaris <jorgesmbox-ml <at> yahoo.es> writes:
<...>
> I have an ndarray A of shape (M,2,2) representing M 2 x 2 matrices.
> Now I want to apply a transform T of shape (2,2) to each of matrix.
> The way I do this now is by iterating over all rows of A
> multiplying the matrices using numpy.dot():
>
> for row in np.arange(A.shape[0]):
> A[row] = np.dot(A[row],T)
>
> but this seems to be slow when M is large and I have the feeling
> there must be a way of doing it better.
>
Well, I think I getting close, but still don't understand exactly what
I am doing:
A = array([[[ 1, 2],
[ 3, 4]],
[[ 5, 6],
[ 7, 8]],
[[ 9, 10],
[11, 12]]])
T = array([[1, 2],
[3, 4]])
np.tensordot(a, T.T, axes=((2,),(1,))) gives
array([[[ 7, 10],
[15, 22]],
[[23, 34],
[31, 46]],
[[39, 58],
[47, 70]]])
which is what I want. The problem is that I only arrived at this result after
trying many axes combinations, and the transpose in T was just intuition (The
idea of using tensordot came from reading various posts in the list). Can
someone help grasp tensordot, the doc is a bit cryptic to me.
Thanks,
Jorges
More information about the NumPy-Discussion
mailing list