# 6-16
def matrixSum():
print "要进行矩阵加法,行列数必须相同"
M=[]
N=[]
res1 = createMat(M,'M')
res2 = createMat(N,'N')
print M
print N
row_m = res1[0]
column_m = res1[1]
row_n = res2[0]
column_n = res2[1]
if row_n!=row_m or column_n!=column_m:
print '行列数不相等!'
return ERROR
row = row_m
column = column_m
sumres = copy.copy(M)
for i in range(row):
for j in range(column):
sumres[i][j] = M[i][j]+N[i][j]
print 'M+N = '
print sumres
return None
def matriixMultiply():
print "要进行矩阵乘法,M的列数必须与N的行数相同"
M=[]
N=[]
res1 = createMat(M,'M')
res2 = createMat(N,'N')
row_m = res1[0]
row_n = res2[0]
column_m = res1[1]
column_n = res2[1]
if column_m != row_n:
print 'M的列数与N的行数不相等!'
return ERROR
print 'M:',M
print 'N:',N
multiplyres = []
for i in range(row_m):
rowlist = [0]*column_n
multiplyres.append(rowlist)
for m in range(column_n):
for i in range(row_m):
for j in range(column_m):
multiplyres[i][m] += M[i][j]*N[j][m]
#很关键 multiplyres的行数=row_m,列数=column_n,column_n有可能大于row_m
print 'M*N = '
print multiplyres
return None
def createMat(mat,name):
print '输入%s的行数和列数' % name
row,column = raw_input('行数:'),raw_input('列数:')
row = int(row)
column = int(column)
for i in range(row):
rowlist = []
for j in range(column):
print '输入%s矩阵第%d行第%d个数' % (name,i+1,j+1)
rowlist.append(int(raw_input()))
mat.append(rowlist)
return row,column
运行结果