Home > Mobile >  Use for loop to check each elements in matrix in python
Use for loop to check each elements in matrix in python

Time:07-24

A = np.arange(2,42).reshape(5,8)
B = np.arange(4,68).reshape(8,8)

C=np.dot(A,B)

how to use for loop to check each element in C is larger than 100 or not, then the output is True or False.

I have no idea because it is a matrix not a number. Is there someone help me please

CodePudding user response:

Do you want to return True, if EVERY element of C is >100? or do you want to create a matrix, whose entries are True or False if the entries of C are >100 or <100?

In both cases I would recommend not using for-loops. For case1,you can try:

print(min(C.flatten())<100)

which will print False, if all elements of C are bigger than 100 and else True (Note that the .flatten command just rewrites the 2D Array into a 1D one temporarily. The shape of C stays in its original state.)

for case2, you can just type

print(C<100)

and it will print a matrix with entries True or False, based on whether C is > or <100 in that entry.

CodePudding user response:

if you want to use for-loops: First note that the shape of C is (5,8), meaning that C is a 2D object. Now, in order to access all entries of C via for-loops, you can write something like this:

import numpy as np
A = np.arange(2,42).reshape(5,8)
B = np.arange(4,68).reshape(8,8)

C=np.dot(A,B)

D = np.zeros(C.shape,dtype = bool)
for i in range(C.shape[0]): #meaning in range 5
    for j in range(C.shape[1]): #meaning in range 8
        if(C[i,j]>100):
            D[i,j] = False
        else:
            D[i,j] = True
print(D)

where I introduced a new matrix D, which is just a new matrix in the same shape of C, in which we consecutively fill up True or False, based on if C is > or <100 at that entry. This code is equivalent, but slower and more complicated than the one I proposed above.

I hope this answers your question sufficiently. If you have any more questions on detials etc., dont hestitate to ask ;).

CodePudding user response:

You must use numpy filter method. This ways that say are very awful and slow. Numpy filtering methods are very optimal

import numpy as np
filter_arr = C > 100
newarr = arr[C]
print(newarr)
  • Related