Reputation: 446
Given a vector v
of length N^2
that holds the entries of a NxN
matrix M
, what is the fastest way to compute the transpose of M
in the same vector representation using NumPy?
I know this can be done by
v.reshape(N, N).T.flatten()
but is this the fastest way?
I am not interested in the intermediate explicit form of M
.
Upvotes: 2
Views: 206
Reputation: 231355
Consider a test case:
In [207]: N=1000
In [208]: X = np.arange(N*N)
Your code:
In [209]: Y = X.reshape(N,N).T.flatten()
In [210]: timeit Y = X.reshape(N,N).T.flatten()
5.45 ms ± 13 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
A suggested alternative:
In [211]: Z = X.reshape(N,N).flatten('F')
In [212]: np.allclose(Y,Z)
Out[212]: True
In [213]: timeit Z = X.reshape(N,N).flatten('F')
5.46 ms ± 39.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
No real difference. reshape
and transpose
are views.
Upvotes: 3