Sunday 9 September 2012

Matrices Multiplication algorithm implementation in python

Matrices Multiplication implementation in python.

I always ignored questions on matrices i rather ran away from those never dared to accept them and code them, finally made up my mind. Next one in line is "inplace" transform of matrix.  Ns ran away ow that i have started programming matrices i feel better to have done something which i always ran away from.

#------------------------------------------------------------------------------- # Name: matrixmultiplication # Purpose: # # Created: 08/09/2012 #------------------------------------------------------------------------------- def main(): mat1=[[1,2,3,4],[3,3,3,4],[5,6,7,8],[5,6,7,8]] mat2=[[1,2,3,4],[1,2,3,4],[5,6,7,8],[5,6,7,8]] mat3=[[9,2],[6,2],[9,7],[5,6]] c = matmulti(mat1,mat2) print(c) def zeros(*shape): if len(shape) == 0: return 0 a = shape[0] b = shape[1:] return [zeros(*b) for i in range(a)] def matmulti(a,b): x=len(a) y=len(a[0]) m=len(b) n=len(b[0]) #print(x,y,m,n) if y != m: print("Canot multipy the matrices as the column count of multiplier is not equal to the row count of the multiplicand") return [] i,j,k,c=0,0,0,zeros(x,n) while i < x: j=0 while j < n: k=0 sum=0 while k < y: sum=sum+(a[i][k]*b[k][j]) k=k+1 c[i][j]=sum j=j+1 i=i+1 return c if __name__ == '__main__': main()

No comments:

Post a Comment