python and matrices

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • 15153681
    New Member
    • Feb 2009
    • 6

    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
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    A matrix or array can be represented by a list of lists.
    Example:
    Code:
    >>> [[0 for _ in range(3)] for _ in range(3)]
    [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    >>>
    You can encapsulate an array object as an instance of a class object. Example:
    Code:
    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 __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 len(self):
            return len(self.data)
        
        def __str__(self):
            return '\n'.join(['Row %s = %s' % (i, self.data[i]) for i in range(self.rows)])
    
        def __repr__(self):
            return 'Matrix(%d, %d)' % (self.rows, self.cols)
    
    # Example
    >>> m0 = Matrix(4,4)
    >>> m0
    Matrix(4, 4)
    >>> print m0
    Row 0 = [0, 0, 0, 0]
    Row 1 = [0, 0, 0, 0]
    Row 2 = [0, 0, 0, 0]
    Row 3 = [0, 0, 0, 0]
    >>> m0[3,3]='a string'
    >>> m0[2,2]=123456
    >>> print m0
    Row 0 = [0, 0, 0, 0]
    Row 1 = [0, 0, 0, 0]
    Row 2 = [0, 0, 123456, 0]
    Row 3 = [0, 0, 0, 'a string']
    >>>
    Another example using a dictionary:
    Code:
    class Darray(object):
        
        def __init__(self, rows, cols):
            self.rows = rows
            self.cols = cols
            # initialize array and fill with zeroes
            self.data = {}
            for row in range(rows):
                for col in range(cols):
                    self.data.setdefault(row, {})[col] = 0
    
        def __setitem__(self, rowcol, v):
            self.data[rowcol[0]][rowcol[1]] = v
    
        def __getitem__(self, rowcol, v):
            return self.data[rowcol[0]][rowcol[1]]
    
        def __str__(self):
            outputList = ['%s%s%s' % ('Row/Col'.center(11), '|', ''.join(['%6s' % i for i in range(0,self.cols)])),]
            outputList.append('=' * 6 * (2+self.cols))
            for key in self.data:
                outputList.append('%s|%s' % (str(key).center(11), ''.join(['%6s' % self.data[key][i] for i in self.data[key]])))
            return '\n'.join(outputList)
        
    if __name__ == '__main__':
        print
        a = Darray(4,6)
        print a
        print
        a[3,4]=19
        a[3,2]=344
        a[0,5]=55
        print a
    Output from above example:
    Code:
    >>> 
      Row/Col  |     0     1     2     3     4     5
    ================================================
         0     |     0     0     0     0     0     0
         1     |     0     0     0     0     0     0
         2     |     0     0     0     0     0     0
         3     |     0     0     0     0     0     0
    
      Row/Col  |     0     1     2     3     4     5
    ================================================
         0     |     0     0     0     0     0    55
         1     |     0     0     0     0     0     0
         2     |     0     0     0     0     0     0
         3     |     0     0   344     0    19     0
    >>>
    If you need more power and efficiency, you can install NumPy to create multi-dimensional arrays. Example:
    Code:
    >>> ar = numpy.array(((0,0,0,0), (1,2,3,4), (5,6,7,8)), float)
    >>> ar
    array([[ 0.,  0.,  0.,  0.],
           [ 1.,  2.,  3.,  4.],
           [ 5.,  6.,  7.,  8.]])
    >>> ar[:2]
    array([[ 0.,  0.,  0.,  0.],
           [ 1.,  2.,  3.,  4.]])
    >>> ar[1:]
    array([[ 1.,  2.,  3.,  4.],
           [ 5.,  6.,  7.,  8.]])
    >>> ar[1]
    array([ 1.,  2.,  3.,  4.])
    >>>

    Comment

    Working...