By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,403 Members | 1,089 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,403 IT Pros & Developers. It's quick & easy.

python and matrices

P: 6
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
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
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

Post your reply

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