adding 2 matrices

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rodrigo carvaja
    New Member
    • Apr 2011
    • 4

    adding 2 matrices

    i'm having a little issue when adding2 matrices on python, according to my understanding the program should be:

    Code:
    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!!
    Last edited by Meetee; May 24 '11, 07:20 AM. Reason: please use code tags
  • Mariostg
    Contributor
    • Sep 2010
    • 332

    #2
    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...

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Since you want a list of lists, you must append a list to z instead of an int. I also corrected your indentation
      Code:
      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

      Comment

      • rodrigo carvaja
        New Member
        • Apr 2011
        • 4

        #4
        Thank you very much it works great!!! :)

        Comment

        Working...