简体   繁体   English

转置存储在 NumPy 中的一维数组中的矩阵的最快方法?

[英]Fastest way to transpose a matrix stored in an 1D array in NumPy?

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?给定一个长度为N^2的向量v包含NxN矩阵M的条目,使用 NumPy 在相同向量表示中计算M的转置的最快方法是什么?

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 .我对M的中间显式形式不感兴趣。

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. reshapetranspose是视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM