#
# title: algebra.py
# author: Nicholas Fitzkee (nickfitzkee at jhu dot edu)
# date: February 16, 2006
# summary: Example of using the matrix module
#
# Description:
#
# A simple (albeit not efficient) way to implement matrices in Python
# is using the idea of a list of lists. The first list stores the
# column list (i.e. a row of numbers), and the second list stores the
# columns. As an example, the following would represent a matrix with
# two rows and four columns:
#
# b = [[4, 0, -2, 3],
# [1, 1, 0, 8]]
#
# In this matrix, to access the second row and third column, we would
# simply need to say b[1][2] (remember zero indexing!). If we wanted
# to change the eight to a 4, this command would suffice:
#
# b[1][3] = 4
#
# While we can implement lists in python in this way, there's still
# alot of work to do: Python by itself cant' add matrices, multiply
# matrices, or do any of the operations that you would like to do with
# these objects. This sounds like a job for a library.
#
# The matrix.py file stores a lot of common functions for matrix algebra,
# as well as some functions that are useful for displaying the matrices
# implemented in this way. This file illustrates how this library
# can be used to solve simple matrix problems
#
import matrix
# initialize matrix a. In this case we start with an identity matrix
# and modifiy values from there. The result is:
#
# [[ 1.0, 4.0, 0.0],
# [-2.0, 1.0, 0.0],
# [ 0.0, 0.0, -6.0]]
#
a = matrix.identity_matrix(3)
a[0][1] = 4.0
a[1][0] = -2.0
a[1][1] = -6.0
# initialize matrix b. Here, we're going to use only the matrix
# functions. The result is
#
# [[3.0, 3.0],
# [3.0, 3.0],
# [3.0, 3.0]]
#
b = matrix.ones_matrix(3, 2)
b = matrix.scalar_multiply(3.0, b)
# initialize matrix c. The result is
#
# [[1.0, -4.0],
# [0.0, 2.0],
# [1.0, -1.0]]
#
c = matrix.zero_matrix(3, 2)
c[0][0] = 1.0
c[0][1] = -4.0
c[1][1] = 2.0
c[2][0] = 1.0
c[2][1] = -1.0
# Now that we have the matrices, let's display them to the screen.
print 'Matrix a:'
matrix.print_matrix(a, 4, 1)
print ''
print 'Matrix b:'
matrix.print_matrix(b, 4, 1)
print ''
print 'Matrix c:'
matrix.print_matrix(c, 4, 1)
print ''
# Let's do some simple operations:
print 'Sum of b and c:'
matrix.print_matrix(matrix.matrix_add(b, c), 5, 1)
print ''
print 'Difference of b and c:'
matrix.print_matrix(matrix.matrix_subtract(b, c), 5, 1)
print ''
print 'Matrix a raised to the fifth power:'
matrix.print_matrix(matrix.matrix_power(a, 5), 7, 1)
print ''
prod = matrix.matrix_multiply(a, b)
print 'Matrix a times b:'
matrix.print_matrix(prod, 5, 1)
print ''
print 'Matrix a times b that can be pasted into python:'
matrix.python_matrix(prod, 5, 1)