473,287 Members | 1,663 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,287 software developers and data experts.

How To Create A Dictionary Based - Sparse Matrix

10
Hi,

I would like to know how to create a dictionary based matrix. Where column and row are considered in placing my desired value. and will pass value as dictionary

just like this

def __init__(self, mtx={}, m=0, n=0):
Nov 5 '07 #1
5 7863
bartonc
6,596 Expert 4TB
The author of this thread had some wild ideas about using a dictionary to store a matrix.

Your Idea looks much simpler, but we may need a little more info to go on (like an example of usage, etc.).
Nov 5 '07 #2
cLoque
10
hi

this is what i need to figure out. it confuses me because most of the example in creating a sparse vector are in list, mine uses dictionary. i am just a beginner in python, so i really need all the help that i can get in doing this project.

hope you can help me guys


# def __init__(self, mtx={}, m=0, n=0):
The constructor takes as arguments the dictionary representation of a sparse matrix (mtx), along with the row and column dimensions (m and n, respectively), and initializes the corresponding instance variables. The instance dictionary must be a true copy of the dictionary passed in the argument, not just a pointer. We explained in lecture how a true copy is made by the constructor in class SparseVector; the technique is similar here.
Note there is potential for error using this constructor. Specifically, m and/or n could be less than (or equal to) the largest row/column index appearing in the dictionary. This cannot happen. If the matrix dimension is m×n, no row index can be ≥ m and no column index can be ≥ n. Your constructor must detect this error, and if it occurs an exception must be raised. Exceptions are discussed below.

>>>for this one what i understand is i have to initialize or create an empty matrix that will hold the my matrix.


# def __getitem__(self, ij):
[] is overloaded for GeneralSparse matrix element retrieval. Similar to __getitem__() in class SparseVector. There is no need to check for out-of-bounds indices. __getitem__() is used only by methods __add__() and __mul__() of class GeneralSparse, and these methods are protected from out-of-bounds index access (see below).

# def __setitem__(self, ij, val):
[] is overloaded for GeneralSparse matrix element assignment. Similar to __setitem__() in class SparseVector. There is no need to check for out-of-bounds indices (as with __getitem__()).
Nov 5 '07 #3
bartonc
6,596 Expert 4TB
As this is coursework, you'll really need to post work that you have done and seek guidance finding errors in YOUR OWN work. This site has strict policies against doing you coursework for you. Instructions for using CODE tags are on the right hand side of the page and all policies are enumerated in our Posting Guidelines (also linked to from the announcement at the top of the page).
Nov 5 '07 #4
cLoque
10
hi,

i want to hava matrix output by my code doesn't return what i want, hope you can help me with my __str__()

here it is:

Expand|Select|Wrap|Line Numbers
  1. class GeneralSparse:
  2.  
  3.     def __init__(self, mtx={}, m=0, n=0):
  4.         self.matrix = {}
  5.         self.matrix.update(mtx)
  6.         self.row = m
  7.         self.col = n
  8.  
  9.     def __getitem__(self, ij):
  10.         return self.matrix.get(ij,0)   
  11.  
  12.     def __setitem__(self, ij, val):
  13.         self.matrix[i,j] = val
  14.  
  15.     def __str__(self):
  16.         s = "["
  17.         if self.row > 0:
  18.             for i in range(self.row):
  19.                 s += str(self[i])
  20.                 if i < self.row:
  21.                      s += ", "
  22.         for j in range(self.col):
  23.                     s += str(self[j]) 
  24.             s += "]"
  25.         return s
  26.  
  27.  
  28. if __name__=="__main__":
  29.     x = GeneralSparse({(2,1):1}, 2, 3)
  30.     print x
this what i get each time i run this

Expand|Select|Wrap|Line Numbers
  1. Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
  2. Type "copyright", "credits" or "license" for more information.
  3. IDLE 0.8 -- press F1 for help
  4. >>> 
  5. [0, 0000, 000]
  6. [0, 000]
  7. [0, 0000, 000]
  8. [0, 0000, 000]
instead of having a matrix i only get rows and doesn't prints my the desired value just 0

hope you can help me
Nov 7 '07 #5
bvdet
2,851 Expert Mod 2GB
hi,

i want to hava matrix output by my code doesn't return what i want, hope you can help me with my __str__()

here it is:

Expand|Select|Wrap|Line Numbers
  1. class GeneralSparse:
  2.  
  3.     def __init__(self, mtx={}, m=0, n=0):
  4.         self.matrix = {}
  5.         self.matrix.update(mtx)
  6.         self.row = m
  7.         self.col = n
  8.  
  9.     def __getitem__(self, ij):
  10.         return self.matrix.get(ij,0)   
  11.  
  12.     def __setitem__(self, ij, val):
  13.         self.matrix[i,j] = val
  14.  
  15.     def __str__(self):
  16.         s = "["
  17.         if self.row > 0:
  18.             for i in range(self.row):
  19.                 s += str(self[i])
  20.                 if i < self.row:
  21.                      s += ", "
  22.         for j in range(self.col):
  23.                     s += str(self[j]) 
  24.             s += "]"
  25.         return s
  26.  
  27.  
  28. if __name__=="__main__":
  29.     x = GeneralSparse({(2,1):1}, 2, 3)
  30.     print x
this what i get each time i run this

Expand|Select|Wrap|Line Numbers
  1. Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
  2. Type "copyright", "credits" or "license" for more information.
  3. IDLE 0.8 -- press F1 for help
  4. >>> 
  5. [0, 0000, 000]
  6. [0, 000]
  7. [0, 0000, 000]
  8. [0, 0000, 000]
instead of having a matrix i only get rows and doesn't prints my the desired value just 0

hope you can help me
I initialized your self.matrix with zeros, added an __iter__() method, and modified __str__():
Expand|Select|Wrap|Line Numbers
  1. class GeneralSparse(object):
  2.  
  3.     def __init__(self, mtx={}, row=4, col=4):
  4.         self.row = row
  5.         self.col = col
  6.         self.matrix = dict(zip([(i,j) for i in range(row) for j in range(col)], \
  7.                                [0.0 for i in range(row) for j in range(col)]))
  8.         self.matrix.update(mtx)
  9.  
  10.     def __getitem__(self, ij):
  11.         return self.matrix[ij]   
  12.  
  13.     def __setitem__(self, ij, val):
  14.         self.matrix[ij] = val
  15.  
  16.     def __iter__(self):
  17.         keys = self.matrix.keys()
  18.         keys.sort()
  19.         for key in keys:
  20.             yield key, self.matrix[key]
  21.  
  22.     def __str__(self):
  23.         return '{%s}' % ', '.join(['%s: %s' % (item[0], item[1]) for item in self])
  24.  
  25. if __name__=="__main__":
  26.     x = GeneralSparse({(2,1):1}, 3, 6)
  27.     print x
Nov 7 '07 #6

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

Similar topics

4
by: Derek Fountain | last post by:
I'm just starting another PHP project and can see a familiar task not far on the horizon. I have several database record tuples that I need to manipulate - person, department, client, job, etc. -...
8
by: Benjamin Scott | last post by:
Hello. I attempted to build a compound dictionary: len(Lst)=1000 len(nuerLst)=250 len(nuestLst)=500 Dict={}
0
by: George Sakkis | last post by:
Is there any sparse matrix package compatible with Numeric/Numarray ? Ideally, the implementation of a matrix (dense/sparse) should be transparent to the application. However the APIs of the only...
7
by: mariaczi | last post by:
Hi, I code class to storage sparse matrix row compressed and i have a problem with implements method to setVal and addVal. I will replace later this methods overloaded operator(). Please, can You...
4
by: deLenn | last post by:
Hi, Does scipy have an equivalent to Matlab's 'find' function, to list the indices of all nonzero elements in a sparse matrix? Cheers.
3
by: mediratta | last post by:
Hi, I want to allocate memory for a large matrix, whose size will be around 2.5 million x 17000. Three fourth of its rows will have all zeroes, but it is not known which will be those rows. If I...
6
by: hvmclrhu | last post by:
Hi I have a big problem. When we compile serial.c with gcc, I get this error program is generating the sparse matrix Segmentation fault I think ı have to use malloc() but I don't know how to...
5
by: adam.kleinbaum | last post by:
Hi there, I'm a novice C programmer working with a series of large (30,000 x 30,000) sparse matrices on a Linux system using the GCC compiler. To represent and store these matrices, I'd like to...
4
by: ishakteyran | last post by:
hello to all.. i have a realy tough assignment which requires me to add, substract, multiply, and get inverse of non-sparse and sparse matrixes.. in a more clear way it wants me to to the...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
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: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.