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

Share your thoughts