从文件中的数据在Python中构建对称矩阵

从文件中的数据在Python中构建对称矩阵,python,Python,我有一个文件,例如,它看起来像: 1 1 5.5 1 2 6.1 1 3 7.3 2 2 3.4 2 3 9.2 3 3 4.7 这是对称3x3矩阵的一半。我想用Python创建一个完整的对称矩阵 [[ 5.5 6.1 7.3] [ 6.1 3.4 9.2] [ 7.3 9.2 4.7]] 当然,我的实际文件比NxN矩阵大得多,所以我需要一个解决方案,而不是逐个输入值 我已经用尽了我所有的资源——书籍和互联网,而我目前所拥有的并不是很接近。有人能帮我吗 谢谢大家

我有一个文件,例如,它看起来像:

1  1  5.5
1  2  6.1
1  3  7.3
2  2  3.4
2  3  9.2
3  3  4.7
这是对称3x3矩阵的一半。我想用Python创建一个完整的对称矩阵

[[ 5.5 6.1 7.3] 
 [ 6.1 3.4 9.2]
 [ 7.3 9.2 4.7]]
当然,我的实际文件比NxN矩阵大得多,所以我需要一个解决方案,而不是逐个输入值

我已经用尽了我所有的资源——书籍和互联网,而我目前所拥有的并不是很接近。有人能帮我吗


谢谢大家!

要读取文件并将其作为python对象加载,以下是一个解决方案:

import numpy

m = numpy.matrix([[0,0,0],[0,0,0],[0,0,0]])

with file('matrix.txt', 'r') as f:
    for l in f:
        try:
            i, j, val = line.split(' ')
            i, j, val = int(i), int(j), float(val)
            m[i-1,j-1] = val
        except:
            print("couldn't load line: {}".format(l))

print m

这里有一种完全在Numpy内部实现这一点的替代方法。两条重要意见:

您可以使用np.loadtxt函数直接读取 您可以在一行中将上半部分值分配给正确的索引:N[idxs[:,0]-1,idxs[:,1]-1]=vals 代码如下:

import numpy as np    
from StringIO import StringIO

indata = """
1  1  5.5
1  2  6.1
1  3  7.3
2  2  3.4
2  3  9.2
3  3  4.7
"""

infile = StringIO(indata)

A = np.loadtxt(infile)

# A is
# array([[ 1. ,  1. ,  5.5],
#        [ 1. ,  2. ,  6.1],
#        [ 1. ,  3. ,  7.3],
#        [ 2. ,  2. ,  3.4],
#        [ 2. ,  3. ,  9.2],
#        [ 3. ,  3. ,  4.7]])

idxs = A[:, 0:2].astype(int)
vals = A[:, 2]

## To find out the total size of the triangular matrix, note that there
## are only n * (n + 1) / 2 elements that must be specified (the upper
## half amount for (n^2 - n) / 2, and the diagonal adds n to that).
## Therefore, the length of your data, A.shape[0], must be one solution
## to the quadratic equation: n^2 + 1 - 2 * A.shape[0] = 0
possible_sizes = np.roots([1, 1, -2 * A.shape[0]])

## Let us take only the positive solution to that equation as size of the
## result matrix
size = possible_sizes[possible_sizes > 0]

N = np.zeros([size] * 2)

N[idxs[:,0] - 1, idxs[:,1] - 1] = vals

# N is
# array([[ 5.5,  6.1,  7.3],
#        [ 0. ,  3.4,  9.2],
#        [ 0. ,  0. ,  4.7]])

## Here we could do a one-liner like
# N[idxs[:,1] - 1, idxs[:,0] - 1] = vals

## But how cool is it to add the transpose and subtract the diagonal? :)
M = N + np.transpose(N) - np.diag(np.diag(N))

# M is
# array([[ 5.5,  6.1,  7.3],
#        [ 6.1,  3.4,  9.2],
#        [ 7.3,  9.2,  4.7]])

如果您事先知道矩阵的大小,并且听起来像是这样,那么以下内容在Python 2和Python 3中都适用:

N = 3
symmetric = [[None]*N for _ in range(SIZE)]  # pre-allocate output matrix

with open('matrix_data.txt', 'r') as file:
    for i, j, val in (line.split() for line in file if line):
        i, j, val = int(i)-1, int(j)-1, float(val)
        symmetric[i][j] = val
        if symmetric[j][i] is None:
            symmetric[j][i] = val

print(symmetric)  # -> [[5.5, 6.1, 7.3], [6.1, 3.4, 9.2], [7.3, 9.2, 4.7]]

如果您不知道时间的长度,可以对文件进行预处理并确定给定的最大索引值。

到目前为止您尝试了什么?您是否尝试读取文件并将其加载到python对象中?您是否提前知道方阵的大小?如果它是对称的,并且在文件中只指定了一半,那么您还需要添加m[j,i]=Val,谢谢您的输入。这个代码对我来说并没有真正起作用,但经过几次修改后,我让它起作用了。我必须在循环中使用m[i-1,j-1],因为i和j从1开始,应该从0开始。我还使用了m=numpy.matlib.zerosN,N,因为我正在处理大的NxN矩阵。感谢Againffyi,在堆栈溢出时说谢谢的正确方式是,以及何时你会有足够的声誉来做这件事-