有没有一种更快的方法可以使用 numpy 从多个矩阵创建 3x3 矩阵以进行特征值和特征向量计算?

发布于 2025-01-17 11:31:34 字数 534 浏览 4 评论 0原文

我正在尝试计算多个 3x3 矩阵的特征值和特征向量。我有 6 个(e11、e12、e13、e22、e23、e33)mxn 形状的矩阵,每个 3x3 矩阵都是使用这 6 个矩阵中的每个元素形成的。这6个矩阵中的元素数量为数千个。现在我只是循环遍历这些矩阵并在每次传递时创建一个 3x3 矩阵并计算特征值和特征向量,计算时间几乎需要 10 分钟。我知道一定有更好的方法。我不是 python 专家,因此任何有助于加快我的代码速度的帮助将不胜感激。

请参阅下面我的代码:

for i in range(0,m):
    for j in range(0,n):
        E = np.array([ [e11[i][j], e12[i][j], e13[i][j]],
                       [e12[i][j], e22[i][j], e23[i][j]],
                       [e13[i][j], e23[i][j], e33[i][j]] ])

        e_val, e_vec = np.linalg.eig(E)

I am trying to calculate eigenvalues and eigenvectors for multiple 3x3 matrices. I have 6 (e11, e12, e13, e22, e23, e33) mxn shaped matrices and each 3x3 matrix is formed using each element from these 6 matrices. The number of elements in these 6 matrices is in the thousands. Right now I just loop through these matrices and create a 3x3 matrix at each pass and calculate eigenvalue and eigenvectors and it takes almost 10 mins to compute. I know there must be a better way. I am not an expert in python so any help to speed up my code would be appreciated.

See my code below:

for i in range(0,m):
    for j in range(0,n):
        E = np.array([ [e11[i][j], e12[i][j], e13[i][j]],
                       [e12[i][j], e22[i][j], e23[i][j]],
                       [e13[i][j], e23[i][j], e33[i][j]] ])

        e_val, e_vec = np.linalg.eig(E)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧竹 2025-01-24 11:31:34

如果我创建一组(3,4)数组,可以将它们结合在一起

In [149]: e11,e12,e22 = [np.ones((3,4))*i for i in range(1,4)]
In [150]: E1=np.stack((np.stack([e11,e12],-1), np.stack([e12,e22],-1)),-1)
In [151]: E1.shape
Out[151]: (3, 4, 2, 2)

,可以传递到eig以生成:

In [153]: np.linalg.eig(E)[0].shape
Out[153]: (3, 4, 2)

我让您概括为(3,3)案例

If I create a set of (3,4) arrays, I can combine them with

In [149]: e11,e12,e22 = [np.ones((3,4))*i for i in range(1,4)]
In [150]: E1=np.stack((np.stack([e11,e12],-1), np.stack([e12,e22],-1)),-1)
In [151]: E1.shape
Out[151]: (3, 4, 2, 2)

That can be passed to eig to produce:

In [153]: np.linalg.eig(E)[0].shape
Out[153]: (3, 4, 2)

I'll let you generalize to your (3,3) case

So要识趣 2025-01-24 11:31:34

根据 @hpaulj 的建议,我修改了代码如下,将计算时间从 10 分钟减少到 40 秒。

E = np.stack([
    np.stack([e11,e12,e13],-1),
    np.stack([e12,e22,e23],-1),
    np.stack([e13,e23,e33],-1)],-1)

e_val, e_vec = np.linalg.eig(E)

所以现在 e_vale_vec 分别具有所有特征值和特征向量。

As per the suggestion from @hpaulj, I modified my code as below which reduced my computation time from 10 min to 40 seconds.

E = np.stack([
    np.stack([e11,e12,e13],-1),
    np.stack([e12,e22,e23],-1),
    np.stack([e13,e23,e33],-1)],-1)

e_val, e_vec = np.linalg.eig(E)

so now the e_val and e_vec have all the eigenvalues and eigenvectors respectively.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文