m122linalg0

799 days ago by jozefl

We'll explore Sage's linear algebra capabilities. First, let's do some matrix multiplication.

A = Matrix([[1,2,3],[3,2,1],[1,1,1]]) w = vector([1,1,-4]) wA=w*A; print 'wA = ',wA Aw=A*w; print 'Aw = ',Aw 
       

For equations of the form

Ax=b

Sage uses the same syntax as Matlab when solving for 'x'. 'A\b' is shorthand for A^-1 b. Of course, not all systems of equations have solutions.

Re-evaluate, changing to

b=vector([0,-4,1])    and then

b=Matrix([0,-4],[1,0])

b=vector([0,-4,-1]) x=A\b x 
       

Let's check our answer.

A*x 
       

Now we'll examine how sage indexes matrices. Note that the coordinate of the first cell in a matrix is defined as [0,0] rather than [1,1]/

print 'A = \n',A print 'A[0,0] = ', A[0,0] print 'A[0,2] = ', A[1,0] 
       

It's easy to screw this up. Here's what happens if we forget and try to retrieve the third entry in the first line with A[1,3].

print 'A[1,3] = ',A[1,3] 
       

Let's change some entries.

A[0,2]=15 print 'A = \n', A 
       
A[0,2]=infinity print 'A = \n',A 
       
A[0,2]=NaN print 'A = \n',A 
       

We can expand the matrix by defining an entry beyond the index.

B=zero_matrix(RR,2,3) Astack=A.stack(B) print 'A stacked on the 2x3 zero matrix: \n',Astack C=zero_matrix(RR,5,1) Aaug=Astack.augment(C) print 'A augmented with the 5x1 zero vector: \n',Aaug Aaug[4,3]=2 print 'A in final form: \n', Aaug 
       

Note that we can't simply add A to the 5x3 zero matrix:

D=zero_matrix(RR,5,4) A+D 
       

Note that we can also store a matrix as a sparse matrix, that is, only storing the coordinates and values of the non-zero entries, in order to save memory. However, it still treats the matrix as an m x n matrix and will return the matrix in proper form when asked.

Asparse=Matrix(QQ,Aaug,sparse=True) print 'Asparse = \n',Asparse 
       

Unlike in Matlab, we can't expand a matrix by defining an entry beyond its dimensions. For example, if we wish to expand A (with zeros) to a 5x4 matrix with the last entry equal to two and we write A[4,3]=2, it will return an 'index out of range' error.


Instead we have to add rows and columns using the 'stack' and 'augment' commands.