Read one specific cell of numpy matrix
Question: I wrote a function to see if a matrix is symmetric or not:

    
    
    def issymmetric(mat):
        if(mat.shape[0]!=mat.shape[1]):
            return 0
        for i in range(mat.shape[0]):
            for j in range(i):
                if (mat[i][j]!=mat[j][i]):
                    return 0
        return 1
    

It works well with built-in ndarrays e.g. numpy.ones:

    
    
    import numpy as np
    a=np.ones((5,5), int)
    print issymmetric(a)
    

And with numpy arrays:

    
    
    import numpy as np
    a=np.array([[1, 2, 3], [2, 1 , 2], [3, 2, 1]])
    print issymmetric(a)
    

But when it comes to numpy matrixes:

    
    
    import numpy as np
    a=np.matrix([[1, 2, 3], [2, 1 , 2], [3, 2, 1]])
    print issymmetric(a)
    

It gaves me this error:

    
    
      File "issymetry.py", line 9, in issymmetric
        if (mat[i][j]!=mat[j][i]):
      File "/usr/lib/python2.7/dist-packages/numpy/matrixlib/defmatrix.py", line 316, in __getitem__
        out = N.ndarray.__getitem__(self, index)
    IndexError: index 1 is out of bounds for axis 0 with size 1
    
    shell returned 1
    

That's because There is no a[0][1]

`a[0]` is `matrix([[1, 2, 3]])`. `a[0][0]` is `matrix([[1, 2, 3]])` too., but
there is no `a[0][1]`.

How can I fix this issue, without changing the matrix type, or the function?

In general, what is the proper way to read and update one specific cell of a
numpy matrix?


Answer: It is best to use `[i,j]` style indexing in `numpy`. Often you can get by with
`[i][j]` when using `np.array`, but not with `np.matrix`. Remember an
`np.matrix` is always 2d.

In a shell construct a simple 2d array, and try different methods of indexing.
Now try it with `np.matrix` arrays. Pay attention to the shape.

    
    
    In [2]: A = np.arange(6).reshape(2,3)
    In [3]: A[1]   # short for A[1,:]
    Out[3]: array([3, 4, 5])    # shape (3,)
    In [4]: A[1][2]   # short for A[1,:][2]
    Out[4]: 5
    In [5]: M=np.matrix(A)
    In [6]: M[1]
    Out[6]: matrix([[3, 4, 5]])   # shape (1,3), 2d
    In [7]: M[1][2]
    ...
    IndexError: index 2 is out of bounds for axis 0 with size 1
    

correct indexing that works with both

    
    
    In [9]: A[1,2]
    Out[9]: 5
    In [10]: M[1,2]
    Out[10]: 5
    

`A[i][j]=...` is also prone to failure when used on the LHS. It only works if
the first part `A[i]` returns a `view`. If fails if it produces a `copy`.

