Help Summing Rows and Columns In A Matrix

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lethek39
    New Member
    • Jun 2007
    • 1

    Help Summing Rows and Columns In A Matrix

    Hey
    I have been trying to figure out how to sum rows and columns in a matrix square. I also have been trying to get the program to list the numbers of the diagonal in the matrix. So far this is the code I have (I am using Python):
    [CODE=python]
    def generate (rows, cols): # This just prints the coordinates and the number that goes in it, It also prints the matrix in a square
    import random
    m = {}
    for r in range(rows):
    for c in range(cols):
    m[r,c]=random.randran ge(100)
    print m

    print "\n"

    for r in range(rows):
    for c in range (cols):
    print str(m[r,c]).rjust(4),
    print
    return m

    def rowsum(m): # This is summing the row
    results = []
    for row in len(m):
    results=sum(m(r ow)) # I think this is were my problem is
    return results

    def columnsum(m): # This is summing the column
    rows = len(m)
    cols = len(m[0]) # I think this is were my other problem is
    result = []
    for c in range(cols):
    sum = 0
    for r in range(rows):
    sum += m[r][c]
    result.append(s um)
    return result

    def diagonal(m): # This shows the numbers from the top left to bottom right diagonal
    diagonal = []
    rows = len(m)
    for row in range(rows):
    diagonal.append (m[row][row]) # I think this is were my final problem is
    return diagonal
    [/CODE]
    The error I am getting is about my rows, columns and diagonals being strings and not numbers. I can do all the summing of the rows and columns and show the numbers in the diagonal just fine using lists. I know the dictionary form of summing the rows and columns and showing the numbers in the diagonal are very similar to the list form, but for the love of me I just can't figure it out. If someone has any ideas on how to best sum the rows and columns and show the numbers in the diagonal the help would be appreciated.
    Last edited by bartonc; Jun 28 '07, 02:33 AM. Reason: Added [CODE=python][CODE] tags.
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Originally posted by lethek39
    Hey
    I have been trying to figure out how to sum rows and columns in a matrix square. I also have been trying to get the program to list the numbers of the diagonal in the matrix. So far this is the code I have (I am using Python):
    [CODE=python]
    def generate (rows, cols): # This just prints the coordinates and the number that goes in it, It also prints the matrix in a square
    import random
    m = {}
    for r in range(rows):
    for c in range(cols):
    m[r,c]=random.randran ge(100)
    print m

    print "\n"

    for r in range(rows):
    for c in range (cols):
    print str(m[r,c]).rjust(4),
    print
    return m

    def rowsum(m): # This is summing the row
    results = []
    for row in len(m):
    results=sum(m(r ow)) # I think this is were my problem is
    return results

    def columnsum(m): # This is summing the column
    rows = len(m)
    cols = len(m[0]) # I think this is were my other problem is
    result = []
    for c in range(cols):
    sum = 0
    for r in range(rows):
    sum += m[r][c]
    result.append(s um)
    return result

    def diagonal(m): # This shows the numbers from the top left to bottom right diagonal
    diagonal = []
    rows = len(m)
    for row in range(rows):
    diagonal.append (m[row][row]) # I think this is were my final problem is
    return diagonal
    [/CODE]
    The error I am getting is about my rows, columns and diagonals being strings and not numbers. I can do all the summing of the rows and columns and show the numbers in the diagonal just fine using lists. I know the dictionary form of summing the rows and columns and showing the numbers in the diagonal are very similar to the list form, but for the love of me I just can't figure it out. If someone has any ideas on how to best sum the rows and columns and show the numbers in the diagonal the help would be appreciated.
    I've added CODE tags to your post. More on that later.

    The syntax
    Code:
    m = {}
    creates an empty dictionary. For matrix work, you'll want to install the NumPy package.

    I'll post an example shortly.

    Thanks for joining the Python Forum on TheScripts.com.

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Originally posted by bartonc
      I've added CODE tags to your post. More on that later.

      The syntax
      Code:
      m = {}
      creates an empty dictionary. For matrix work, you'll want to install the NumPy package.

      I'll post an example shortly.

      Thanks for joining the Python Forum on TheScripts.com.
      Here is the download page for SciPy and NumPy.

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        Originally posted by bartonc
        I've added CODE tags to your post. More on that later.

        The syntax
        Code:
        m = {}
        creates an empty dictionary. For matrix work, you'll want to install the NumPy package.

        I'll post an example shortly.

        Thanks for joining the Python Forum on TheScripts.com.
        [CODE=python]import random
        import numpy




        def generate (rows, cols): # This just prints the coordinates and the number that goes in it, It also prints the matrix in a square
        ## m = {}
        m = numpy.zeros((ro ws, cols), int)
        for r in range(rows):
        for c in range(cols):
        m[r, c] = random.randrang e(100)
        ## print m
        ##
        ## print "\n"
        ##
        ## for r in range(rows):
        ## for c in range (cols):
        ## print str(m[r,c]).rjust(4),
        ## print
        return m

        matrix = generate(4, 4)
        print matrix
        [/CODE]
        [[72 69 51 67]
        [65 14 39 51]
        [84 54 6 2]
        [67 13 3 54]]

        Comment

        • bartonc
          Recognized Expert Expert
          • Sep 2006
          • 6478

          #5
          Originally posted by bartonc
          Here is the download page for SciPy and NumPy.
          Here's a native python list version:[CODE=python]
          def NativeZeros(nRo ws, nCols):
          return [[0 for row in range(nRows)] for col in range(nCols)]



          matrix = NativeZeros(4, 4)
          print matrix
          matrix[2][2] = 11
          for item in matrix:
          print item[/CODE]
          [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
          [0, 0, 0, 0]
          [0, 0, 0, 0]
          [0, 0, 11, 0]
          [0, 0, 0, 0]

          Comment

          • bartonc
            Recognized Expert Expert
            • Sep 2006
            • 6478

            #6
            Originally posted by bartonc
            Here's a native python list version:[CODE=python]
            def NativeZeros(nRo ws, nCols):
            return [[0 for row in range(nRows)] for col in range(nCols)]



            matrix = NativeZeros(4, 4)
            print matrix
            matrix[2][2] = 11
            for item in matrix:
            print item[/CODE]
            [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
            [0, 0, 0, 0]
            [0, 0, 0, 0]
            [0, 0, 11, 0]
            [0, 0, 0, 0]
            These techniques use a thing called list comprehension. Here's an example of using one to sum the entire matrix:[CODE=python]
            def NativeZeros(nRo ws, nCols):
            return [range(nRows) for col in range(nCols)]



            matrix = NativeZeros(4, 4)
            print matrix
            print sum([sum(row) for row in matrix])[/CODE]
            [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
            24

            Comment

            • bartonc
              Recognized Expert Expert
              • Sep 2006
              • 6478

              #7
              Originally posted by bartonc
              These techniques use a thing called list comprehension. Here's an example of using one to sum the entire matrix:[CODE=python]
              def NativeZeros(nRo ws, nCols):
              return [range(nRows) for col in range(nCols)]



              matrix = NativeZeros(4, 4)
              print matrix
              print sum([sum(row) for row in matrix])[/CODE]
              [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
              24
              Here's the column summer:[CODE=python]
              print sum([row[3] for row in matrix])[/CODE]
              12

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                Here is a simple matrix class I have played with in the past and this AM:[code=Python]
                class Matrix(object):
                def __init__(self, rows, cols):
                self.rows = rows
                self.cols = cols
                # initialize matrix and fill with zeroes
                self.data = [[0 for _ in range(cols)] for _ in range(rows)]

                def sumRow(self, row):
                return sum(self.data[row])

                def sumCol(self, col):
                return sum([row[col] for row in self.data])

                def sumDiag(self, startCol):
                colList = [startCol+i for i in range(self.cols )]
                for i, item in enumerate(colLi st):
                if item > self.cols-1:
                colList[i] -= self.cols
                return sum([row[col] for row,col in zip(self.data, colList)])

                def sumDiag2(self, startCol):
                num = max(self.cols, self.rows)
                colList = [startCol+i for i in range(num)]
                rowList = range(num)
                for i in range(len(colLi st)):
                while colList[i] > self.cols-1:
                colList[i] -= self.cols
                for i in range(len(rowLi st)):
                while rowList[i] > self.rows-1:
                rowList[i] -= self.rows
                return sum([self.data[row][col] for row,col in zip(rowList, colList)])

                def __setitem__(sel f, pos, v):
                self.data[pos[0]][pos[1]] = v

                def __getitem__(sel f, pos):
                return self.data[pos[0]][pos[1]]

                def __iter__(self):
                for row in self.data:
                yield row

                def __str__(self):
                outStr = ""
                for i in range(self.rows ):
                outStr += 'Row %s = %s\n' % (i, self.data[i])
                return outStr

                def __repr__(self):
                return 'Matrix(%d, %d)' % (self.rows, self.cols)[/code]and some interaction:[code=Python]>>> import random
                >>> b = Matrix(4,8)
                >>> for row in b:
                ... for i in range(b.cols):
                ... row[i] = random.randrang e(100)
                ...
                >>> b
                Matrix(4, 8)
                >>> print b
                Row 0 = [77, 61, 7, 76, 66, 88, 74, 7]
                Row 1 = [87, 2, 52, 42, 99, 55, 6, 16]
                Row 2 = [19, 42, 95, 89, 17, 59, 71, 12]
                Row 3 = [87, 12, 76, 55, 49, 56, 5, 0]

                >>> b.sumCol(3)
                262
                >>> b.sumRow(0)
                456
                >>> sum([77, 61, 7, 76, 66, 88, 74, 7])
                456
                >>> b.sumDiag(0)
                229
                >>> b.sumDiag2(0)
                421
                >>> b.sumDiag2(3)
                451
                >>> [/code]Can someone improve the sum diagonal methods?

                Comment

                Working...