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

3 Replies

 100+ P: 332 Look at the indention level of return x at line 10. Your function stops when it executes the return. Also, if you want a 3 by 3 matrix returned, you will have to provide indices to z when you populate it otherwise you will get a 1 by 9 matrix... May 24 '11 #2

 Expert Mod 2.5K+ P: 2,851 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 def sumamat(a,b):     z=[]     for i in range (n):         tem = []         for j in range (n):             x=m1[i][j]+m2[i][j]             tem.append(x)         z.append(tem)     return z May 24 '11 #3

 P: 4 Thank you very much it works great!!! :) May 24 '11 #4 