439,941 Members | 1,753 Online
Need help? Post your question and get tips & solutions from a community of 439,941 IT Pros & Developers. It's quick & easy.

 P: 4 i'm having a little issue when adding2 matrices on python, according to my understanding the program should be: Expand|Select|Wrap|Line Numbers m1=[[1,3,9],[5,6,3],[2,5,8]] m2=[[1,3,9],[5,6,3],[2,5,8]] n=3 def sumamat(a,b):     z=[]     for i in range (n):         for j in range (n):             x=m1[i][j]+m2[i][j]             z.append(x)         return z   print(sumamat(m1,m2)) being n the number of rows and columns since for my purposes, all the matrices are going to be N x N as a result i get: [2, 6, 18] when i sould get: [[2, 6, 18],[10,12,6],[4,10,16]] i know i'm doing it the wrong way, i just don't know how to fix it, any help would be greatly appreciated!! May 24 '11 #1

Since you want a list of lists, you must append a list to z instead of an int. I also corrected your indentation
Expand|Select|Wrap|Line Numbers
1. def sumamat(a,b):
2.     z=[]
3.     for i in range (n):
4.         tem = []
5.         for j in range (n):
6.             x=m1[i][j]+m2[i][j]
7.             tem.append(x)
8.         z.append(tem)
9.     return z