访问矩阵中的元素索引

Accessing element index in a matrix

我想在矩阵中保存一个元素的索引如下

cx = []
for j in range(len(self.correctors_indexes)):
    self.lattice[self.correctors_indexes[j]].KickAngle = [self.dkick, 0.00]

    lindata0, tune, chrom, lindata = self.lattice.linopt(get_chrom=True, refpts=self.BPM_indexes)    
    closed_orbitx = lindata['closed_orbit'][:, 0]
    cx.append(closed_orbitx)

    [row, col] = cx.index(str(closed_orbitx))
    file = open("orm_x_CXY_"+ [row, col] +".txt", "w")
    str1 = repr(self.lattice[self.correctors_indexes[j]].KickAngle)
    file.write(str1)
    file.close()

    Cx = np.squeeze(cx) / self.dkick
    return Cx

但是我收到错误消息

cannot unpack non-iterable int object

相反,我尝试添加“查找”功能:

def find(element, matrix):
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] == element:
                return (i, j)

我使用它如下:

[row, col] = find(closed_orbitx , cx)
file = open("orm_x_CXY_"+ [row, col] +".txt", "w")

但是我得到了错误

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如何提取矩阵中的元素索引并在文件名中使用?

您可以使用函数 np.argwhere 获取数组或矩阵中某个值的索引,然后将这些值用作文件名。请参阅以下示例:

element = 4
mat = np.array([
    [0, 1, 2],
    [3, 4, 5], 
    [6, 7, 8],
])

idxs = np.argwhere(mat == element)

print(idxs[0])  # --> [1, 1]

# Unpack the row and column index
row, col = idxs[0]

# You can then use the pair in a filename like
fname = f"file_{row}-{col}.txt"

# or similarly
fname = "file_{}-{}.txt".format(row, col)

但是请注意,np.argwhere 总是 returns 一个索引数组。