计算矩阵中两行的所有组合的点积

2024-04-30 00:55:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编程非常陌生,我正试图计算N*3矩阵中任意两行的所有组合的点积

例如,对于N=5,我有一个矩阵

   [0.64363829, 0.21027068, 0.7358777 ],
   [0.39138384, 0.49072791, 0.7784631 ],
   [0.22952251, 0.90537974, 0.35722115],
   [0.40108871, 0.88992243, 0.21717715],
   [0.06710475, 0.84022499, 0.53806962]

我想计算所有行组合的点积,比如:row1*row2,row1*row3,row1*row4,row1*row5,row2*row3。。。第4行*第5行

我不知道如何解决这个问题,所以我试了一些方法。到目前为止我已经

for i in range(N-1): 
    for l in range(1, N): 
        dotms = (np.dot(nmag[(i),:], nmag[(i+l),:]))
        print(dotms)

其中nmag是5*3矩阵

输出只有7个答案,但有5行我要找10个不同的组合

[0.92794896,0.60097537,0.60509647,0.6158193,0.81220999, [分别为0.76275382、0.85745291]

提前感谢您的帮助


Tags: 方法infor编程range矩阵row1row2
2条回答

我不知道我是否误解了你的意思,但是nmag.dot(nmag.T)会得到你想要的吗

In [5]: nmag.dot(nmag.T)
Out[5]:
array([[1.        , 0.92794895, 0.60097537, 0.60509647, 0.6158193 ],
       [0.92794895, 0.99999999, 0.81220999, 0.76275381, 0.85745291],
       [0.60097537, 0.81220999, 1.00000001, 0.9753569 , 0.96833458],
       [0.60509647, 0.76275381, 0.9753569 , 1.        , 0.89150645],
       [0.6158193 , 0.85745291, 0.96833458, 0.89150645, 1.        ]])

如果你只想得到不同行的点积

In [17]: res = nmag.dot(nmag.T)

In [18]: [res[i, j] for i in range(res.shape[0]) for j in range(res.shape[1]) if i<j]
Out[18]:
[0.9279489524047824,
 0.6009753676942861,
 0.6050964675806133,
 0.6158193009466447,
 0.8122099927113468,
 0.7627538110746328,
 0.8574529124107328,
 0.9753568970221529,
 0.9683345820770881,
 0.8915064490330812]

你的循环索引不太适合你的任务:

import numpy as np
nmag = np.array([[0.64363829, 0.21027068, 0.7358777 ],
                 [0.39138384, 0.49072791, 0.7784631 ],
                 [0.22952251, 0.90537974, 0.35722115], 
                 [0.40108871, 0.88992243, 0.21717715],
                 [0.06710475, 0.84022499, 0.53806962]])

for i in range(N-1):  # iterate over all rows but the last
    for j in range(i+1, N):   # start j from i+1 
        dotms = np.dot(nmag[i, :], nmag[j, :])
        print(dotms)

相关问题 更多 >