matrix multiplication
Seb
spluque at gmail.com
Tue Feb 27 11:02:54 EST 2018
On Tue, 27 Feb 2018 07:36:31 -0700,
Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Tue, Feb 27, 2018 at 4:08 AM, Peter Otten <__peter__ at web.de> wrote:
>> Seb wrote:
>>> On Tue, 27 Feb 2018 12:25:30 +1300,
>>> Gregory Ewing <greg.ewing at canterbury.ac.nz> wrote:
>>>> Seb wrote:
>>>>> I was wondering is whether there's a faster way of multiplying
>>>>> each row (1x3) of a matrix by another matrix (3x3), compared to
>>>>> looping through the matrix row by row as shown in the code.
>>>> Just multiply the two matrices together.
>>>> If A is an nx3 matrix and B is a 3x3 matrix, then C = A @ B is an
>>>> nx3 matrix where C[i] = A[i] @ B.
>>>> (This is a property of matrix multiplication in general, nothing
>>>> special about numpy.)
>>> I think that's only true if B is the same for every row in A. In
>>> the code I posted, B varies by row of A.
>> Yeah, you would have to substitute the N 3x3 matrices with an Nx3x3
>> tensor, though I don't know if numpy provides an op such that
>> Nx3 op Nx3x3 --> desired result
>> or
>> op(Nx3, Nx3x3) --> desired result
> Nx1x3 @ Nx3x3 ought to do it, with the result being Nx1x3.
That's right. I just tried this manipulation by replacing the last
block of code in my example, from the line above `for` loop with:
---<--------------------cut here---------------start------------------->---
# Alternative using `np.matmul`
uvw_alt = uvw.reshape((uvw.shape[0], 1, uvw.shape[1]))
bmats = np.asarray(map(randint_mat, maxint))
uvw_rots_alt = np.matmul(uvw_alt, bmats).squeeze()
---<--------------------cut here---------------end--------------------->---
Interestingly, the time savings from IPython are not spectacular:
%run -t -N100 loop_approach.py
IPython CPU timings (estimated):
Total runs performed: 100
Times : Total Per run
User : 0.28 s, 0.00 s.
System : 0.00 s, 0.00 s.
Wall time: 0.28 s.
%run -t -N100 matmul_approach.py
IPython CPU timings (estimated):
Total runs performed: 100
Times : Total Per run
User : 0.17 s, 0.00 s.
System : 0.00 s, 0.00 s.
Wall time: 0.18 s.
--
Seb
More information about the Python-list
mailing list