Examples of Access matrix elements, rows and columns in Python Programming

0

Similar like lists, we can access matrix elements using index. 

All Contributions

how we can slice a matrix:

import numpy as np
A = np.array([[1, 4, 5, 12, 14], 
    [-5, 8, 9, 0, 17],
    [-6, 7, 11, 19, 21]])
print(A[:2, :4])  # two rows, four columns
''' Output:
[[ 1  4  5 12]
 [-5  8  9  0]]
'''
print(A[:1,])  # first row, all columns
''' Output:
[[ 1  4  5 12 14]]
'''
print(A[:,2])  # all rows, second column
''' Output:
[ 5  9 11]
'''
print(A[:, 2:5])  # all rows, third to the fifth column

Access matrix elements :

import numpy as np
M = np.array([2, 4, 6, 8, 10])

print("M[0] =", M[0])     # First element     
print("M[2] =", M[2])     # Third element 
print("M[-1] =", M[-1])   # Last element     

Access columns of a Matrix :

import numpy as np

M = np.array([[2, 3, 6, 11], 
    [-4, 7, 8, 0],
    [-5, 9, 12, 17]])
print("M[:,0] =",M[:,0]) # First Column
print("M[:,1] =", M[:,1]) # Fourth Column
print("M[:,-2] =", M[:,-2]) # Last Column (4th column in this case)

Access rows of a Matrix

import numpy as np
K = np.array([[1, 4, 5, 12], 
    [-5, 8, 9, 0],
    [-6, 7, 11, 19]])
print("K[0] =", K[0]) # First Row
print("K[2] =", K[2]) # Third Row
print("K[-1] =", K[-1]) # Last Row (3rd row in this case)

how we can access elements of a two-dimensional array (which is basically a matrix):

import numpy as np
M = np.array([[1, 4, 5, 12],
    [-5, 8, 9, 0],
    [-6, 7, 11, 19]])
#  First element of first row
print("M[0][0] =", M[0][0])  
# Third element of second row
print("M[1][2] =", M[1][2])
# Last element of last row
print("M[-1][-1] =", M[-1][-1])

 

total contributions (6)

New to examplegeek.com?

Join us