這裏是完全做到這裏面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對象中? – zmo
並查看['numpy'](http://www.numpy.org/) – zmo
您是否事先知道方矩陣的大小? – martineau