Python - Matrix and Matrix function representation

> Procedural Languages > Python

1 - About

How Matrix and Matrix function representation are modelled in Python.

3 - Representations

3.1 - Matrix

Python Matrix representation:

  • A list of row-lists
  • A list of column-lists
Advertising

3.1.1 - column-list

0 −1 −2 −3
1  0 −1 −2
2  1  0 −1
[[i-j for i in range(3)] for j in range(4)]
[[0, 1, 2], [-1, 0, 1], [-2, -1, 0], [-3, -2, -1]]

3.1.2 - row-list

matrix=[]
 
for x in range(0, 5):
    matrix.append(["O"] * 5)
 
def print_matrix(matrix):
    for row in matrix:
        print " ".join(row)
 
print "Length Matrix:"+str(len(matrix))
 
print
print "The Matrix"
print_matrix(matrix)
 
matrix[0][3]="1"
matrix[2][4]="2"
matrix[4][0]="3"
 
print
print "The New Matrix"
print_matrix(matrix)
Length Matrix:5

The Matrix
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O

The New Matrix
O O O 1 O
O O O O O
O O O O 2
O O O O O
3 O O O O

3.2 - Function

In Python, the Matrix function is represented by a Dictionary of:

  • entry
  • rows
  • or columns

Example of Matrix A_(i,j) of A[i,j]

j=@ j=# j=%
i=a 1 2 3
i=b 4 5 6
Advertising

3.2.1 - Entry

{('a','@'):1, ('a','#'):2, ('a', '%'):3, ('b', '@'):10, ('b', '#'):20, ('b','?'):30}

3.2.2 - Row

{'a': {'@':1, '#':2, '%':3}, 'b': {'@':10, '#':20, '?':30}}

3.2.3 - Column

{'@': {'a':1, 'b':10}, '#': {'a':2, 'b':20}, '?': {'a':3, 'b':30}}

3.2.4 - Others

column1 = {'row1' : 'value1_column1', 'row2' : 'value2_column1'}
column2 = {'row1' : 'value1_column2', 'row2' : 'value2_column2'}
matrixDict = {'column1':column1, 'column2': column2 }
print matrixDict
 
print 'Length matrix: ', len(matrixDict)
 
for column in matrixDict:
    print column
    attributes = matrixDict[column]
    for attribute in attributes:
        print '  - ', attribute, ':', attributes[attribute]
{'column1': {'row1': 'value1_column1', 'row2': 'value2_column1'}, 'column2': {'row1': 'value1_column2', 'row2': 'value2_column2'}}
Length matrix:  2
column1
  -  row1 : value1_column1
  -  row2 : value2_column1
column2
  -  row1 : value1_column2
  -  row2 : value2_column2