473,390 Members | 1,521 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,390 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 7878
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 mn, 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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.