Python Matrix

What is a matrix?

A matrix is a two-dimensional data structure. In real-world tasks you often have to store rectangular data table. The table below shows the marks of three students in different subjects.
S.No
Student Name
Science
English
History
Arts
Maths
1
Roy
80
75
85
90
95
2
John
75
80
75
85
100
3
Dave
80
80
80
90
95
Such tables are called matrices or two-dimensional arrays. In python any table can be represented as a list of lists (a list, where each element is in turn a list).
For example:
A = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
In the above example A represents a 3*6 matrix where 3 is number of rows and 6 is number of columns.

How to create a matrix?

In python, matrix is a nested list. A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.

Example 1: Create a matrix in python

Here's a program that creates a numerical table with 3 rows and 6 columns.
# a is 2-D matrix with integers
a = [['Roy',80,75,85,90,95],
     ['John',75,80,75,85,100],
     ['Dave',80,80,80,90,95]]

#b is a nested list but not a matrix
b= [['Roy',80,75,85,90,95],
    ['John',75,80,75],
    ['Dave',80,80,80,90,95]]
In the above examples a is a matrix as well as nested list where as b is a nested list but not a matrix.

Example 2: Create a dynamic matrix using for loop in python

A possible way: you can create a matrix of n*m elements by first creating a list of nelements (say, of n zeros) and then make each of the elements a link to another one-dimensional list of m elements:
n = 3
m = 4
a = [0] * n
for i in range(n):
    a[i] = [0] * m
print(a)
When you run the program, the output will be:
[[0 0 0 0], 
 [0 0 0 0], 
 [0 0 0 0]]

Example 3: Create a matrix using numpy in pyhton

Another way to create a matrix is using numpy library.
from numpy import * 

x = range(16)

x = reshape(x,(4,4)) 

print(x) 
When you run the program, the output will be
[[0 1 2 3], 
 [4 5 6 7], 
 [8 9 10 11], 
 [12 13 14 15]]

How to access elements in a matrix?

There are various ways in which we can access elements of a python matrix.

List Index

Similar to list we can access elements of a matrix by using square brackets [] after the variable like a[row][col]

Example 4: Accessing elements of the matrix in python by using list index

# a is 2-D matrix with integers
a = [['Roy',80,75,85,90,95],
     ['John',75,80,75,85,100],
     ['Dave',80,80,80,90,95]]

print(a[0])

print(a[0][1])

print(a[1][2])
When you run the program, the output will be:
['Roy', 80, 75, 85, 90, 95]
80
80Here a is a matrix that contains name and marks of the students.
To see all the marks for the student Roy, we have accessed it by a[0] where 0 is 1st row of the matrix. This gives the output ['Roy',80,75,85,90,95].
Similarly, we can view only his marks in Science by accessing the position of it a[0][1]where 0 is 1st row and 1 is the 2nd column of the matrix. This gives the output 80.
If we wanted to view John's marks in English by accessing the position of it a[1][2] where 1 is 2nd row and 2 is the 3rd column of the matrix. This gives the output 80.

Negative Indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

Example 5: Accessing elements of the matrix in python by using negative list index

a = [['Roy',80,75,85,90,95],
     ['John',75,80,75,85,100],
     ['Dave',80,80,80,90,95]]
 
print(a[-1]) 
 
print(a[-1][-2]) 

print(a[-2][-3]) 
When you run the above program, the output will be
['Dave', 80, 80, 80, 90, 95]
90
75
Here a is a matrix that contains name and marks of the students.
To see all the marks for the student Dave, we have accessed it by a[-1] where -1 is last row of the matrix. This gives the output ['Dave', 80, 80, 80, 90, 95].
Similarly, we can view only his marks in Arts by accessing the position of it a[-1][-2] where -1 is last row and -2 is the second last column of the matrix. This gives the output 90.
If we wanted to view John's marks in History by accessing the position of it a[-2][-3] where -2 is second last row and -3 is the third last column of the matrix. This gives the output 75.

Why and how to slice matrix in python?

In the students matrix we store marks for different subjects of three students. Suppose we want to access marks of Science for all 3 students, here we will be using slicing to get the sub elements of the matrix. In python slicing is done using colon(:) with a syntax (start:end:increment) but for matrix we have to do it using numpy library.
We use slicing to get specific sets of sub-elements from it, without any long, drawn out for loops.

Example 6: Slicing a matrix in python using colon(:)  and numpy

from numpy import *

a = array([['Roy',80,75,85,90,95],
           ['John',75,80,75,85,100],
           ['Dave',80,80,80,90,95]])

print(a[:3,[0,1]])
When we run the above program, the output will be
[['Roy',80],
  ['John',75],
  ['Dave',80]]
Here we have created the matrix a by using array() method from numpy.
Since we have to access Roy's and John's Science marks with their names, we used a[:3,[0,1]] where :3 is for firts three rows and [0,1] is for the first two columns.

How to change or add elements of a matrix?

In python list are mutable, meaning, their elements can be changed unlike string or tuple.
We can use assignment operator (=) to change an item or a range of items.

Example 7: Change elements of a matrix in python

a = [['Roy',80,75,85,90,95],
     ['John',75,80,75,85,100],
     ['Dave',80,80,80,90,95]]

b=a[0]
print(b)

b[1]=75
print(b)

a[2]=['Sam',82,79,88,97,99]
print(a)

a[0][4]=95
print(a)
When we run the above program, the output will be
b=['Roy',80,75,85,90,95]

b=['Roy',75,75,85,90,95]

a= [['Roy',75,75,85,90,95],
    ['John',75,80,75,85,100],
    ['Sam',82,79,88,97,99]]

a=[['Roy',75,75,85,95,95],
   ['John',75,80,75,85,100],
   ['Sam',82,79,88,97,99]]
Here a is a matrix where we have stored name and marks of the students.
We have stored Roy's marks row in the variable b, by using it's row position from the matrix which is 0 so it becomes a[0].
To change Roy's marks in Science, by directly accessing that position where the marks is stored; as the position of that is a[0][1]. So, in b it will be b[1].
We replaced Dave's row with a new student's marks Sam; we directly accessed the row position which is a[2] of Dave's marks and replace it by Sam's marks .
Roy's marks in Arts was entered wrong, we accessed the position a[0][4] where 0 is the first row and 4 is the fifth column of the matrix in which the data is stored and assigned a new value.

Python operators to add elements in matrix

We can add one row to a matrix using append() method and add a item using insert()method by importing numpy library.
Now we will be adding a new row in the students table or matrix which contains a new student's marks.

Example 8: Adding a new row in the matrix in python using append()

from numpy import *

a = array([['Roy',80,75,85,90,95],
        ['John',75,80,75,85,100],
        ['Dave',80,80,80,90,95]])

a= append(a,[['Sam',82,79,88,97,99]],0)
//here 0 is axis that represent dimensions where 0 stands for row and 1 stands is column

print(a)
When we run the above program, the output will be
[['Roy',80,75,85,90,95],
 ['John',75,80,75,85,100],
 ['Dave',80,80,80,90,95],
 ['Sam',82,79,88,97,99]]
Here we have created the matrix a using array() method from numpy library.
We are using append() method from numpy to add a row in the matrix where a is the matrix, ['Sam',82,79,88,97,99] is the new row and 0 is the axis that represents the row.

Example 9: Add a new column in the matrix for economics marks using insert().

from numpy import * 

a = array([['Roy',80,75,85,90,95],
      ['John',75,80,75,85,100],
      ['Dave',80,80,80,90,95]]) 

a= insert(a,[6],[[73],[80],[85]],axis=1) 
//here axis represents the dimensions where 0 stands for row and 1 stands for column 

print(a) 
When we run the above program, the output will be
[['Roy',80,75,85,90,95,73],
 ['John',80,75,80,75,85,100,80],
 ['Dave',85,80,80,80,90,95,85]]
Here we have created the matrix a using array() method from numpy library.
We are using insert() method from numpy to add a column in the matrix where a is the matrix, [6] is the column where we have to insert the values, [[73],[80],[85]] is the new column and 1 is the axis that represents the column.

Concatenation of matrix in Python

We can also use + operator to combine two different lists. This is also called concatenation.

Example 10: Add a row in the matrix in python using +

a=[['Roy',80,75,85,90,95],
    ['John',75,80,75,85,100],
    ['Dave',80,80,80,90,95]]

a= a+ [['Sam',82,79,88,97,99]]

print(a)
When we run the above program, the output will be
[['Roy',80,75,85,90,95],
 ['John',75,80,75,85,100],
 ['Dave',80,80,80,90,95],
 ['Sam',82,79,88,97,99]]
Here a is a matrix where we have stored name and marks of the students.
We have inserted a new row using + at the end of the matrix.

How to delete or remove elements from a matrix?

We can delete an entire row of items from a matrix using the method delete from numpylibrary. 

Example 11: Delete a row of a matrix in python using delete from numpy

from numpy import *

a = array([['Roy',80,75,85,90,95],
      ['John',75,80,75,85,100],
      ['Dave',80,80,80,90,95]])

a= delete(a,[1],0)

print(a)
When we run the above program, the output will be
[['Roy',80,75,85,90,95],
 ['Dave',80,80,80,90,95]]
Here we have created the matrix a using array() method from numpy library.
We are using delete() method from numpy to delete a row in the matrix where a is the matrix, [1] is the second row and 0 is the axis that represents the row.

Delete an entire column of a matrix in Python

Example 12: Delete columns of a matrix in python using delete from numpy

from numpy import *

a = array([['Roy',80,75,85,90,95],
      ['John',75,80,75,85,100],
      ['Dave',80,80,80,90,95]])

a= delete(a, s_[1::2], 1)

print(a)
When we run the above program, the output will be
[['Roy' ,75, 90],
 ['John', 80, 85],
 ['Dave', 80, 90]]
Here we have created the matrix a using array() method from numpy library.
We are using delete() method from numpy to delete a column in the matrix where a is the matrix, s_[1::2] are the columns second, third and fourth to be deleted and 1 is the axis that represents the column.

Read also : Python Data Types

Thank you :)

Comments

  1. Good post!Thank you so much for sharing this pretty post,it was so good to read and useful to improve my knowledge as updated one,keep blogging.
    Python training in Electronic City

    ReplyDelete

Post a Comment

Popular posts from this blog

Angular : List of Topics

What are the steps involved in the concreting Process?