user3104335
user3104335

Reputation: 13

Check if values in matrix matches with values from array and return the matrix index if not

So I have a matrix with a dataset and I would like a function that compares all the values from the matrix with an array to check if the values in the matrix is present in the array and if not returns the index of the value.

I have tried setting up a dobbelt for loop in the

#the array with the values the matrixs values is compared 
Grades=np.array([-3,0,2,4,7,10,12])

#the dobbelt for loop
for u in range(0,len(data)):
        for j in range(0,len(data.T)):
            if not data[u,j] in Grades:
                # Error message is printed if a values isn't a found in the array.
                print("Error in {}, {}".format(u,j))

I got error in all of the values... Error in 1,2, Error in 1,3, Error in 1,4, Error in 1,5...Error in 10,4, Error in 10,5, Error in 10,6, Error in 10,7

Upvotes: 1

Views: 265

Answers (1)

Abdur Rehman
Abdur Rehman

Reputation: 1101

As you did not give data in question so I am assuming data as 3*3 matrix but this code will work for every matrix.

Grades=np.array([-3,0,2,4,7,10,12])
data = np.array([[1,2,3], [4,5,6], [7,8,9]])

#the dobbelt for loop
for u in range(data.shape[0]):
        for j in range(data.shape[1]):
            if data[u,j] not in Grades:
                # Error message is printed if a values isn't a found in the array.
                print("Error in {} for {} - {}".format(data[u,j], u,j))

Output:

Error in 1 for 0 - 0    # 1 is not present in given array and it's index is (0, 0)
Error in 3 for 0 - 2
Error in 5 for 1 - 1
Error in 6 for 1 - 2
Error in 8 for 2 - 1
Error in 9 for 2 - 2

I hope this would resolve your query.

Upvotes: 0

Related Questions