Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – accessing elements and parts of a matrix


Let's experiment with different ways to access individual elements and parts of a matrix. Enter and evaluate the following code:

 A = Matrix(QQ, [[0, -1, -1, 1], [1, 1, 1, 1], [2, 4, 1, -2],
    [3, 1, -2, 2]])
print("Matrix A:")
show(A)

# Getting elements of a matrix
print("A[0] = {0}".format(A[0]))
print("A[1, 2] = {0}".format(A[1, 2]))
print("A[2, 1] = {0}".format(A[2, 1]))
print("A[0:2]")
show(A[0:2])
print("A[0, 2:4] = {0}".format(A[0, 2:4]))
print("A[:,0]:")
show(A[:,0])

# Getting parts of a matrix
print("Third row:")
print(A.row(2))
print("Second column:")
print(A.column(1))
print("Lower right submatrix:")
show(A.submatrix(2, 2, 2, 2))

The result should look like this:

What just happened?

The individual elements of a matrix are accessed using a pair of indices separated by a comma. The first index selects the row, and the second selects the column. Like all Python sequence types, the indices start at zero. When you access...