-1

How i can find the index number is available in matrix or not? Like

import numpy as np

R= np.matrix ([1,2,34,4,5,5,6,9], 
              [1,2,34,4,5,5,6,9],
              [1,2,34,4,5,5,6,9])

Here i want to search my input index is available or not in "R"

Here my input index is C[4,4]

I want to find if C[4,4] index is available then he returns True otherwise False Please help me how i can find.

usman1644
  • 123
  • 1
  • 2
  • 10

2 Answers2

1

You can just check the dimensions of the matrix.... np.matrix.shape

Pythonista
  • 11,377
  • 2
  • 31
  • 50
  • @ Pythonista You mean instead of "np.matrix" , i need to add "np.matrix.shape" But when i did like this R= np.matrix.shape ([1,2,34,4,5,5,6,9], [1,2,34,4,5,5,6,9], [1,2,34,4,5,5,6,9]) it is giving an error 'getset_descriptor ' object is not callable – usman1644 Nov 15 '18 at 14:03
0

Your matrix definition lacks surrounding [ .... ].


You can either use the Ask for forgiveness not permission approach or test if your given indexes do not exceed the shape of the matrix:

import numpy as np

R = np.matrix ([             # missing [
    [1,2,34,4,5,5,6,9], 
    [1,2,34,4,5,5,6,9],
    [1,2,34,4,5,5,6,9]
])                           # missing ]

print( R.shape )  # (3,8)



def indexAvailable(M,a,b):
    # ask forgiveness not permission by simply accessing it
    # when testing for if its ok to access this    
    try:
        p = M[a,b]
    except:
        return False
    return True

print(99,22,indexAvailable(R,99,22))
print(9,2,indexAvailable(R,9,2))
print(2,2,indexAvailable(R,2,2))

Output:

99 22 False
9 2 False
2 2 True

Or you can check all your given indexes against the shape of your matrix:

def indexOk(M,*kwargs):
    """Test if all arguments of kwargs must be 0 <= value < value in M.shape"""
    try: 
        return len(kwargs) == len(M.shape) and all(
            0 <= x < M.shape[i] for i,x in enumerate(kwargs))
    except:
        return False

print(indexOk(R,1,1))    # ok
print(indexOk(R,1,1,1))  # too many dims
print(indexOk(R,3,7))    # first too high
print(indexOk(R,2,8))    # last too high
print(indexOk(R,2,7))    # ok

Output:

True
False
False
False
True
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69