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

python and matrices

hey guys
I'm new to python... and I would like to know how do I create a matrix in python, if anyone can help, it would be appreciated. Thanx
Feb 17 '09 #1
1 9697
bvdet
2,851 Expert Mod 2GB
A matrix or array can be represented by a list of lists.
Example:
Expand|Select|Wrap|Line Numbers
  1. >>> [[0 for _ in range(3)] for _ in range(3)]
  2. [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
  3. >>> 
You can encapsulate an array object as an instance of a class object. Example:
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 __setitem__(self, pos, v):
  9.         self.data[pos[0]][pos[1]] = v
  10.  
  11.     def __getitem__(self, pos):
  12.         return self.data[pos[0]][pos[1]]
  13.  
  14.     def __iter__(self):
  15.         for row in self.data:
  16.             yield row
  17.  
  18.     def len(self):
  19.         return len(self.data)
  20.  
  21.     def __str__(self):
  22.         return '\n'.join(['Row %s = %s' % (i, self.data[i]) for i in range(self.rows)])
  23.  
  24.     def __repr__(self):
  25.         return 'Matrix(%d, %d)' % (self.rows, self.cols)
  26.  
  27. # Example
  28. >>> m0 = Matrix(4,4)
  29. >>> m0
  30. Matrix(4, 4)
  31. >>> print m0
  32. Row 0 = [0, 0, 0, 0]
  33. Row 1 = [0, 0, 0, 0]
  34. Row 2 = [0, 0, 0, 0]
  35. Row 3 = [0, 0, 0, 0]
  36. >>> m0[3,3]='a string'
  37. >>> m0[2,2]=123456
  38. >>> print m0
  39. Row 0 = [0, 0, 0, 0]
  40. Row 1 = [0, 0, 0, 0]
  41. Row 2 = [0, 0, 123456, 0]
  42. Row 3 = [0, 0, 0, 'a string']
  43. >>> 
Another example using a dictionary:
Expand|Select|Wrap|Line Numbers
  1. class Darray(object):
  2.  
  3.     def __init__(self, rows, cols):
  4.         self.rows = rows
  5.         self.cols = cols
  6.         # initialize array and fill with zeroes
  7.         self.data = {}
  8.         for row in range(rows):
  9.             for col in range(cols):
  10.                 self.data.setdefault(row, {})[col] = 0
  11.  
  12.     def __setitem__(self, rowcol, v):
  13.         self.data[rowcol[0]][rowcol[1]] = v
  14.  
  15.     def __getitem__(self, rowcol, v):
  16.         return self.data[rowcol[0]][rowcol[1]]
  17.  
  18.     def __str__(self):
  19.         outputList = ['%s%s%s' % ('Row/Col'.center(11), '|', ''.join(['%6s' % i for i in range(0,self.cols)])),]
  20.         outputList.append('=' * 6 * (2+self.cols))
  21.         for key in self.data:
  22.             outputList.append('%s|%s' % (str(key).center(11), ''.join(['%6s' % self.data[key][i] for i in self.data[key]])))
  23.         return '\n'.join(outputList)
  24.  
  25. if __name__ == '__main__':
  26.     print
  27.     a = Darray(4,6)
  28.     print a
  29.     print
  30.     a[3,4]=19
  31.     a[3,2]=344
  32.     a[0,5]=55
  33.     print a
Output from above example:
Expand|Select|Wrap|Line Numbers
  1. >>> 
  2.   Row/Col  |     0     1     2     3     4     5
  3. ================================================
  4.      0     |     0     0     0     0     0     0
  5.      1     |     0     0     0     0     0     0
  6.      2     |     0     0     0     0     0     0
  7.      3     |     0     0     0     0     0     0
  8.  
  9.   Row/Col  |     0     1     2     3     4     5
  10. ================================================
  11.      0     |     0     0     0     0     0    55
  12.      1     |     0     0     0     0     0     0
  13.      2     |     0     0     0     0     0     0
  14.      3     |     0     0   344     0    19     0
  15. >>> 
If you need more power and efficiency, you can install NumPy to create multi-dimensional arrays. Example:
Expand|Select|Wrap|Line Numbers
  1. >>> ar = numpy.array(((0,0,0,0), (1,2,3,4), (5,6,7,8)), float)
  2. >>> ar
  3. array([[ 0.,  0.,  0.,  0.],
  4.        [ 1.,  2.,  3.,  4.],
  5.        [ 5.,  6.,  7.,  8.]])
  6. >>> ar[:2]
  7. array([[ 0.,  0.,  0.,  0.],
  8.        [ 1.,  2.,  3.,  4.]])
  9. >>> ar[1:]
  10. array([[ 1.,  2.,  3.,  4.],
  11.        [ 5.,  6.,  7.,  8.]])
  12. >>> ar[1]
  13. array([ 1.,  2.,  3.,  4.])
  14. >>> 
Feb 17 '09 #2

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

Similar topics

3
by: François Miville-Dechêne | last post by:
I find your language very nice, it is actually more than three quarters of what I had been dreaming for years a programming language should be. But I mourn the passing of APL, another interpreted...
9
by: Carl | last post by:
I have been using Python for quite some time now and I love it. I use it mainly for explorative computing and numerical prototyping, ie testing and trying out different kinds of algorithms and...
16
by: Roman Suzi | last post by:
Hi, I wonder, does Python support generic programming paradigm, and to what extent (I guess, it doesn't do it in full)? And (or) does it move in that direction? Will we ever see concept...
1
by: Nils Wagner | last post by:
Hi all, Has someone written a C binding to transfer matrices from C to Python and vice versa ? Any pointer would be appreciated. Nils
44
by: Iwan van der Kleyn | last post by:
Please ignore if you are allergic to ramblings :-) Despite a puritan streak I've always tried to refrain from language wars or syntax bickering; call it enforced pragmatism. That's the main...
5
by: C. Barnes | last post by:
Hi, I'm in the process of writing a Python linear algebra module. The current targeted interface is: http://oregonstate.edu/~barnesc/temp/linalg/ The interface was originally based on...
2
by: Zhengzheng Pan | last post by:
Hi all, I'm trying to check whether a (stochastic/transition) matrix converges, i.e. a function/method that will return True if the input matrix sequence shows convergence and False otherwise....
3
by: mosi | last post by:
Python matrices are usually defined with numpy scipy array or similar. e.g. I would like to have easier way of defining matrices, for example: Any ideas how could this be done? The ";" sign...
270
by: Jordan | last post by:
Hi everyone, I'm a big Python fan who used to be involved semi regularly in comp.lang.python (lots of lurking, occasional posting) but kind of trailed off a bit. I just wrote a frustration...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...
0
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...
0
tracyyun
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.