Showing posts with label Matrix. Show all posts
Showing posts with label Matrix. Show all posts

Cloning and Comparing Matrices Using Python

Learn python programming in 12 lessons


The last post showed you how to create and print nxn matrices. This one would show you how to create a copy a matrix and how to compare two matrix to check if they are equal. The first thing you need to understand about checking if two matrices are equal is that you need to check each and every element at each index in both matrix to see if they match. Take this example of a shell interaction

a = [[1,2,3],[4,5,6],[7,8,9]]
a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = a.copy()
b
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
a == b
True
#make changes to one element in a
a[2][2] = 0
a
[[1, 2, 3], [4, 5, 6], [7, 8, 0]]
b
[[1, 2, 3], [4, 5, 6], [7, 8, 0]]
a == b
True
#was expecting the comparison to yield False

 There seem to be an error because a change was made in matrix a but it seems like this change cascaded to matrix b. Since changes were made to a, we expect it to be [[1, 2, 3], [4, 5, 6], [7, 8, 0]] and matrix b remain [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. When the comparison is made, we expect the answer to be False. But because the copy operator only pointed the variable b to the same memory location of matrix a, changes made to matrix a are also reflected in matrix b. This is definitely not what we want. To ensure that this mix up does not happen, we write out own copy and compare functions to our exact specification.

The clone matrix would like like this


def cloneMatrix(matrix):
    """return a copy of the matrix"""
    # create a dummy clone of the same size
    clone = createMatrix( len(matrix) ) #initialize dummy clone with zeros
    for i in range(len(matrix)):
        for j in range(len(matrix)):
            clone[i][j] = matrix[i][j] # replace all zeros in the clone matrix
    return clone

The output looks like this


cloneMatrix([[1,2],[3,4]])
[[1, 2], [3, 4]]
cloneMatrix([[1,2,3],[4,5,6],[7,8,9]])
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The function to compare the matrices would take two matrix as parameters and it looks like this

def matrixEqual(matrixA, matrixB):
    """check if the two 2d matrix are equal - return boolean value"""
    one, two = matrixA, matrixB
  
    # check if the two are the same size
    if len(one) != len(two):
        return False
    else:
        for i in range( len(one) ):
            for j in range( len(two) ):
                if one[i][j] != two[i][j]:
                    return False #break out of loop if a mismatch found
                else:
                    continue # continue checking if the items match
    return True

The output looks like this if run from the Python shell

# compare 2x2 matrix
matrixEqual([[1,1],[1,1]],[[1,1],[1,1]])
True
matrixEqual([[1,1],[1,1]],[[1,1],[1,0]])
False
matrixEqual([
[1,1],
[1,1]],
[
[1,1],
[1,0]])
False
# compare 3x3 matrix
matrixEqual( [[1,2,3], [4,5,6], [7,8,9]], [ [1,2,3], [4,5,6], [7,8,9]] )
True
matrixEqual( [[1,2,3], [4,5,6], [7,0,9]], [ [1,2,3], [4,5,6], [7,8,9]] )
False
read more

Creating and Printing 2 Dimensional Arrays Using Python

Learn python programming in 12 lessons


A matrix in Python is represented as a 2 dimensional array.

Creating a matrix is done by creating a single list of lists. In other words, a matrix in Python is an array that contains other arrays. Here are examples of matrices of different sizes:
2x2 -- [[0,0], [0,0]]
3x3 -- [[0,0,0], [0,0,0], [0,0,0]]
4x4 -- [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]

The steps you need to take when creating an nxn matrix are as follow
create a single empty list
repeat the steps below n times
           create another list with a single element
           multiply that list by n
           add that list to the outer list

Below is the Python code to create an nxn matrix


def createMatrix(n):
    """creates a matrix of size nxn"""
   
    matrix = [] # the outer matrix
   
    for i in range (n):
        matrix.append ([0] * n) #creates a 2-d list of size nxn
   
    return matrix

If the function above is executed, the output would look like this

createMatrix(1)
[[0]]
createMatrix(2)
[[0, 0], [0, 0]]
createMatrix(3)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
createMatrix(4)
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
createMatrix(5)
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]


When it comes to printing the matrix, you would prefer to see rows and columns on the screen. This is achieved by printing each element in the list separately one list under the other. The Python code below does just that.


def printMatrix(matrix):
    """print out a nxn matrix"""
   
    for i in range( len(matrix) ): # for the rows
        for j in range( len(matrix) ): #for the columns
            print( matrix[i][j], end=' ' ) # prints one row
        print() # move to the next level

The output of the following function is as follow


printMatrix(createMatrix(2))
0 0
0 0
printMatrix(createMatrix(3))
0 0 0
0 0 0
0 0 0
printMatrix(createMatrix(4))
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
printMatrix(createMatrix(5))
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

Below is the full code including the main method


 def createMatrix(n):
    """creates a matrix of size nxn"""
   
    matrix = [] # the outer matrix
   
    for i in range (n):
        matrix.append ([0] * n) #creates a 2-d list of size nxn
   
    return matrix


def printMatrix(matrix):
    """print out a nxn matrix"""
   
    for i in range( len(matrix) ): # for the rows
        for j in range( len(matrix) ): #for the columns
            print( matrix[i][j], end=' ' ) # prints one row
        print() # move to the next level
       
def main():
    print("\n\n2x2 matrix\n")
    printMatrix(createMatrix(2))
    print("\n\n3x3 matrix\n")
    printMatrix(createMatrix(3))
    print("\n\n4x4 matrix\n")
    printMatrix(createMatrix(4))
    print("\n\n5x5 matrix\n")
    printMatrix(createMatrix(5))


if __name__ == "__main__":
    main()
read more