Home > Net >  Accessing element index in a matrix
Accessing element index in a matrix

Time:03-02

I want to save the index of an element in a matrix as following

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

But i received the error

cannot unpack non-iterable int object

Instead i tried to add the function "find":

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)

And i used it as following:

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

But i got the error

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

How can i extract the element index in a matrix and use in in the files names?

CodePudding user response:

Thanks, it works, but what about the remaining indices of idxs ? dose it mean that the element appears many time in the matrix in different indices ? @FabianGD

CodePudding user response:

You may use the function np.argwhere to get the indices of a value within an array or a matrix and later use these values for a filename. See the following example:

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)

Note however that np.argwhere always returns an array of indices.

  • Related