By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,941 Members | 1,753 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,941 IT Pros & Developers. It's quick & easy.

adding 2 matrices

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
  1. m1=[[1,3,9],[5,6,3],[2,5,8]]
  2. m2=[[1,3,9],[5,6,3],[2,5,8]]
  3. n=3
  4. def sumamat(a,b):
  5.     z=[]
  6.     for i in range (n):
  7.         for j in range (n):
  8.             x=m1[i][j]+m2[i][j]
  9.             z.append(x)
  10.         return z
  11.  
  12. 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

✓ answered by bvdet

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

Share this Question
Share on Google+
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

bvdet
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
  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
May 24 '11 #3

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

Post your reply

Sign in to post your reply or Sign up for a free account.