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): -
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.randrange(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(row)) # 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(sum)
-
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
-
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.
7 14983 bartonc 6,596
Recognized Expert Expert
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): -
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.randrange(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(row)) # 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(sum)
-
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
-
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
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.
bartonc 6,596
Recognized Expert Expert
I've added CODE tags to your post. More on that later.
The syntax
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.
bartonc 6,596
Recognized Expert Expert
I've added CODE tags to your post. More on that later.
The syntax
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.
- 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((rows, cols), int)
-
for r in range(rows):
-
for c in range(cols):
-
m[r, c] = random.randrange(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
-
[[72 69 51 67]
[65 14 39 51]
[84 54 6 2]
[67 13 3 54]]
bartonc 6,596
Recognized Expert Expert Here is the download page for SciPy and NumPy.
Here's a native python list version: -
def NativeZeros(nRows, 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
[[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]
bartonc 6,596
Recognized Expert Expert
Here's a native python list version: -
def NativeZeros(nRows, 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
[[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: -
def NativeZeros(nRows, nCols):
-
return [range(nRows) for col in range(nCols)]
-
-
-
-
matrix = NativeZeros(4, 4)
-
print matrix
-
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
bartonc 6,596
Recognized Expert Expert
These techniques use a thing called list comprehension. Here's an example of using one to sum the entire matrix: -
def NativeZeros(nRows, nCols):
-
return [range(nRows) for col in range(nCols)]
-
-
-
-
matrix = NativeZeros(4, 4)
-
print matrix
-
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: -
print sum([row[3] for row in matrix])
12
bvdet 2,851
Recognized Expert Moderator Specialist
Here is a simple matrix class I have played with in the past and this AM: -
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(colList):
-
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(colList)):
-
while colList[i] > self.cols-1:
-
colList[i] -= self.cols
-
for i in range(len(rowList)):
-
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__(self, pos, v):
-
self.data[pos[0]][pos[1]] = v
-
-
def __getitem__(self, 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)
and some interaction: - >>> import random
-
>>> b = Matrix(4,8)
-
>>> for row in b:
-
... for i in range(b.cols):
-
... row[i] = random.randrange(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
-
>>>
Can someone improve the sum diagonal methods?
Sign in to post your reply or Sign up for a free account.
Similar topics |
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 which to do it.
As you can see from the object definition that it corresponds to a
function that takes two inputs. When I try to run the script it does
nothing. So what is wrong and how do I fix it? Here is the script.
function...
|
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 structure as follows:
typedef double (*Rowptr); // Holds rows of 4 doubles
|
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 .80 .99
I've written code to calculate the correlation data and it is populated in a
vector like this:
|
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
4 4 4 4 0
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
|
by: kilter |
last post by:
Anyone know of a routine that will return the number of rows and
columns in a matrix?
| |
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 ;
|
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 Fault) raised in your program."
Ill put my code below. can anyone see why it is doing this?
/* Program Function: Reads in data on a boolean matrix (/s) and outputs
* whether the file has parity, is corrupt or the coordinates of the bit...
|
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"
#include<iostream>
#include<iomanip>
#include<fstream>
#include"math.h"
|
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 check to see if the two matrices are able to be multiplied.
This is the code that I have so far:
#include "stdafx.h"
#include <iostream>
using namespace std;
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |