473,241 Members | 1,502 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

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):
Expand|Select|Wrap|Line Numbers
  1. def generate (rows, cols): # This just prints the coordinates and the number that goes in it, It also prints the matrix in a square
  2.     import random
  3.     m = {}
  4.     for r in range(rows):
  5.        for c in range(cols):
  6.             m[r,c]=random.randrange(100)
  7.     print m
  8.  
  9.     print "\n"
  10.  
  11.     for r in range(rows):
  12.         for c in range (cols):
  13.             print str(m[r,c]).rjust(4),
  14.         print
  15.     return m
  16.  
  17. def rowsum(m): # This is summing the row
  18.      results = []
  19.      for row in len(m): 
  20.         results=sum(m(row))  # I think this is were my problem is
  21.      return results
  22.  
  23. def columnsum(m): # This is summing the column
  24.      rows = len(m)
  25.      cols = len(m[0])  # I think this is were my other problem is
  26.      result = []
  27.      for c in range(cols):
  28.          sum = 0
  29.          for r in range(rows):
  30.              sum += m[r][c]
  31.          result.append(sum)
  32.      return result
  33.  
  34. def diagonal(m):  # This shows the numbers from the top left to bottom right diagonal
  35.      diagonal = []
  36.      rows = len(m)
  37.      for row in range(rows):
  38.          diagonal.append(m[row][row]) # I think this is were my final problem is
  39.      return diagonal
  40.  
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.
Jun 28 '07 #1
7 14923
bartonc
6,596 Expert 4TB
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):
Expand|Select|Wrap|Line Numbers
  1. def generate (rows, cols): # This just prints the coordinates and the number that goes in it, It also prints the matrix in a square
  2.     import random
  3.     m = {}
  4.     for r in range(rows):
  5.        for c in range(cols):
  6.             m[r,c]=random.randrange(100)
  7.     print m
  8.  
  9.     print "\n"
  10.  
  11.     for r in range(rows):
  12.         for c in range (cols):
  13.             print str(m[r,c]).rjust(4),
  14.         print
  15.     return m
  16.  
  17. def rowsum(m): # This is summing the row
  18.      results = []
  19.      for row in len(m): 
  20.         results=sum(m(row))  # I think this is were my problem is
  21.      return results
  22.  
  23. def columnsum(m): # This is summing the column
  24.      rows = len(m)
  25.      cols = len(m[0])  # I think this is were my other problem is
  26.      result = []
  27.      for c in range(cols):
  28.          sum = 0
  29.          for r in range(rows):
  30.              sum += m[r][c]
  31.          result.append(sum)
  32.      return result
  33.  
  34. def diagonal(m):  # This shows the numbers from the top left to bottom right diagonal
  35.      diagonal = []
  36.      rows = len(m)
  37.      for row in range(rows):
  38.          diagonal.append(m[row][row]) # I think this is were my final problem is
  39.      return diagonal
  40.  
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
Expand|Select|Wrap|Line Numbers
  1. 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.
Jun 28 '07 #2
bartonc
6,596 Expert 4TB
I've added CODE tags to your post. More on that later.

The syntax
Expand|Select|Wrap|Line Numbers
  1. 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.
Jun 28 '07 #3
bartonc
6,596 Expert 4TB
I've added CODE tags to your post. More on that later.

The syntax
Expand|Select|Wrap|Line Numbers
  1. 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.
Expand|Select|Wrap|Line Numbers
  1. import random
  2. import numpy
  3.  
  4.  
  5.  
  6.  
  7. def generate (rows, cols): # This just prints the coordinates and the number that goes in it, It also prints the matrix in a square
  8. ##    m = {}
  9.     m = numpy.zeros((rows, cols), int)
  10.     for r in range(rows):
  11.         for c in range(cols):
  12.             m[r, c] = random.randrange(100)
  13. ##    print m
  14. ##
  15. ##    print "\n"
  16. ##
  17. ##    for r in range(rows):
  18. ##        for c in range (cols):
  19. ##            print str(m[r,c]).rjust(4),
  20. ##        print
  21.     return m
  22.  
  23. matrix = generate(4, 4)
  24. print matrix
  25.  
[[72 69 51 67]
[65 14 39 51]
[84 54 6 2]
[67 13 3 54]]
Jun 28 '07 #4
bartonc
6,596 Expert 4TB
Here is the download page for SciPy and NumPy.
Here's a native python list version:
Expand|Select|Wrap|Line Numbers
  1. def NativeZeros(nRows, nCols):
  2.     return [[0 for row in range(nRows)] for col in range(nCols)]
  3.  
  4.  
  5.  
  6. matrix = NativeZeros(4, 4)
  7. print matrix
  8. matrix[2][2] = 11
  9. for item in matrix:
  10.     print item
[[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]
Jun 28 '07 #5
bartonc
6,596 Expert 4TB
Here's a native python list version:
Expand|Select|Wrap|Line Numbers
  1. def NativeZeros(nRows, nCols):
  2.     return [[0 for row in range(nRows)] for col in range(nCols)]
  3.  
  4.  
  5.  
  6. matrix = NativeZeros(4, 4)
  7. print matrix
  8. matrix[2][2] = 11
  9. for item in matrix:
  10.     print item
[[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:
Expand|Select|Wrap|Line Numbers
  1. def NativeZeros(nRows, nCols):
  2.     return [range(nRows) for col in range(nCols)]
  3.  
  4.  
  5.  
  6. matrix = NativeZeros(4, 4)
  7. print matrix
  8. print sum([sum(row) for row in matrix])
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
24
Jun 28 '07 #6
bartonc
6,596 Expert 4TB
These techniques use a thing called list comprehension. Here's an example of using one to sum the entire matrix:
Expand|Select|Wrap|Line Numbers
  1. def NativeZeros(nRows, nCols):
  2.     return [range(nRows) for col in range(nCols)]
  3.  
  4.  
  5.  
  6. matrix = NativeZeros(4, 4)
  7. print matrix
  8. print sum([sum(row) for row in matrix])
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
24
Here's the column summer:
Expand|Select|Wrap|Line Numbers
  1. print sum([row[3] for row in matrix])
12
Jun 28 '07 #7
bvdet
2,851 Expert Mod 2GB
Here is a simple matrix class I have played with in the past and this AM:
Expand|Select|Wrap|Line Numbers
  1. class Matrix(object):
  2.     def __init__(self, rows, cols):
  3.         self.rows = rows
  4.         self.cols = cols
  5.         # initialize matrix and fill with zeroes
  6.         self.data = [[0 for _ in range(cols)] for _ in range(rows)]
  7.  
  8.     def sumRow(self, row):
  9.         return sum(self.data[row])
  10.  
  11.     def sumCol(self, col):
  12.         return sum([row[col] for row in self.data])
  13.  
  14.     def sumDiag(self, startCol):
  15.         colList = [startCol+i for i in range(self.cols)]
  16.         for i, item in enumerate(colList):
  17.             if item > self.cols-1:
  18.                 colList[i] -= self.cols
  19.         return sum([row[col] for row,col in zip(self.data, colList)])
  20.  
  21.     def sumDiag2(self, startCol):
  22.         num = max(self.cols, self.rows)
  23.         colList = [startCol+i for i in range(num)]
  24.         rowList = range(num)
  25.         for i in range(len(colList)):
  26.             while colList[i] > self.cols-1:
  27.                 colList[i] -= self.cols
  28.         for i in range(len(rowList)):
  29.             while rowList[i] > self.rows-1:
  30.                 rowList[i] -= self.rows
  31.         return sum([self.data[row][col] for row,col in zip(rowList, colList)])
  32.  
  33.     def __setitem__(self, pos, v):
  34.         self.data[pos[0]][pos[1]] = v
  35.  
  36.     def __getitem__(self, pos):
  37.         return self.data[pos[0]][pos[1]]
  38.  
  39.     def __iter__(self):
  40.         for row in self.data:
  41.             yield row
  42.  
  43.     def __str__(self):
  44.         outStr = ""
  45.         for i in range(self.rows):
  46.             outStr += 'Row %s = %s\n' % (i, self.data[i])
  47.         return outStr
  48.  
  49.     def __repr__(self):
  50.         return 'Matrix(%d, %d)' % (self.rows, self.cols)
and some interaction:
Expand|Select|Wrap|Line Numbers
  1. >>> import random
  2. >>> b = Matrix(4,8)
  3. >>> for row in b:
  4. ...     for i in range(b.cols):
  5. ...         row[i] = random.randrange(100)
  6. ...         
  7. >>> b
  8. Matrix(4, 8)
  9. >>> print b
  10. Row 0 = [77, 61, 7, 76, 66, 88, 74, 7]
  11. Row 1 = [87, 2, 52, 42, 99, 55, 6, 16]
  12. Row 2 = [19, 42, 95, 89, 17, 59, 71, 12]
  13. Row 3 = [87, 12, 76, 55, 49, 56, 5, 0]
  14.  
  15. >>> b.sumCol(3)
  16. 262
  17. >>> b.sumRow(0)
  18. 456
  19. >>> sum([77, 61, 7, 76, 66, 88, 74, 7])
  20. 456
  21. >>> b.sumDiag(0)
  22. 229
  23. >>> b.sumDiag2(0)
  24. 421
  25. >>> b.sumDiag2(3)
  26. 451
  27. >>> 
Can someone improve the sum diagonal methods?
Jun 28 '07 #8

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

Similar topics

7
by: greenflame | last post by:
I am trying to make a matrix object. I have given it some properites. I am trying to add a method. When I call the method by Test.showDims(...) I want to only enter one input, that is the method by...
7
by: Jim | last post by:
Hi people. I was hoping someone could help me as this is driving me up the wall. I'm trying to write a program that deals with matrix multiplication. The Program uses a couple of typedefined...
10
by: Nevets Steprock | last post by:
I'm writing a web program where one of the sections is supposed to output a correlation matrix. The typical correlation matrix looks like this: ..23 ..34 .54 ..76 .44 .28 ..02 .77 ...
4
by: rburdette | last post by:
I need to do a sum of rows and sum of columns in Visual Basic. Is there another way to do it other than the one I have below? 5 7 3 9 12 4 8 9 13 4 0 -`1 -7 13 8...
6
by: kilter | last post by:
Anyone know of a routine that will return the number of rows and columns in a matrix?
8
by: mohammaditraders | last post by:
#include <iostream.h> #include <stdlib.h> #include <conio.h> #include <string.h> class Matrix { private : int numRows, numCols ; int elements ;
8
by: Dameon99 | last post by:
my program compiles without problems but when i try to run it pauses shortly and then crashes. When i set it to debug it came up with the following message: "An Access Violation (Segmentation...
3
by: crazygrey | last post by:
Hello, I'm a newbie to C++ so excuse me if my question was trivial but it is important to me. I'm implementing a simple code to find the forward kinematics of a robot: #include "stdafx.h"...
1
by: dcatunlucky | last post by:
Ok, I have an assignment to write a program that multiplies two matrices. The matrices dimensions will be user defined as well as the numbers (floating point values) inside of them. The program must...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.