26 ตุลาคม 2558

Lab6 Matrix

def setup():
   matrix = [[1,2,3], [6,5,4], [7,8,9]]
   matrix2  =[[7,3,3], [6,1,2], [5,6,1]]
   print("matrix 1 :")
   displayMatrix(matrix)
   print()
   print("matrix 2 :")
   displayMatrix(matrix2)
   print()
   addMatrix(matrix,matrix2)
   print()
   subtractMatrix(matrix , matrix2)
   print()
   multiplyMatrix(matrix, matrix2)
   print()
   transposeMatrix(matrix)


def displayMatrix(matrix):
   row = 0
   while(row<len(matrix)):
      column = 0
      while(column<len(matrix[row])):
         print(matrix[row][column]," ",end="")
         column+=1
      print()
      row+=1
   
def addMatrix(matrix, matrix2):
   row = 0
   print("Add matrix :")
   while(row<len(matrix)):
      column = 0
      while(column<len(matrix[row])):
         print(matrix[row][column]+matrix2[row][column]," ",end="")
         column+=1
      print()
      row+=1
def subtractMatrix(matrix , matrix2):
   row = 0
   print("Subtract matrix :")
   while(row<len(matrix)):
      column = 0
      while(column<len(matrix[row])):
         print(matrix[row][column]-matrix2[row][column]," ",end="")
         column+=1
      print()
      row+=1

def multiplyMatrix(matrix1, matrix2):
   if(len(matrix1[0])==len(matrix2)):#if(column number of matrix1 == row number of matrix2)
      row = 0  
      print("Multiply matrix :")
      while(row<len(matrix1)):#loop for shift row of multiplicand matrix
         column = 0
         while(column<len(matrix2[row])):#loop for shift column of multiplier matrix
            k = 0
            val = 0
            while(k<len(matrix1[row])):#loop for shift column of multiplicand matrix and shift row of multiplier matrix
               val += matrix1[row][k]*matrix2[k][column]#matrix_row[i]_column[k]*matrix2_row[k]_column[j]
               k+=1
            print(val," ",end="")
            column+=1
         print()
         row+=100
   else:
      print("Can't multiply matrix")
      print("Column number of multiplicand matrix not equal row number of multiplier matrix")
   
   
def transpose(matrix):
    i = 0
    j = 0
    while i < len(matrix):
         j += i
         while (j < len(matrix[i])):
            dataCopy = matrix[i][j]
            matrix[i][j] = matrix[j][i]
            matrix[j][i] = dataCopy
            j+=1
         print(matrix[i])
         j = 0
         i+=1
    displayMatrix(matrix)
   


setup()

ไม่มีความคิดเห็น:

แสดงความคิดเห็น