Lecture Notes on 7 Nov 2012
# In all these matrix operations we would like to
# keep the original matrix intact
# reverse the rows of a matrix
def reverse_rows (b):
c = []
for i in range (len(b)):
a = b[i][:]
a.reverse()
c.append(a)
return c
# reverse the columns of a matrix
def reverse_cols (b):
c = []
for i in range (len(b) - 1, -1, -1):
c.append (b[i])
return c
# sum the rows of a matrix
def sum_rows (b):
for i in range (len(b)):
print (sum(b[i]))
# sum the columns of a matrix
def sum_cols (b):
num_cols = len (b[0])
for j in range (num_cols):
sum = 0
for i in range (len (b)):
sum = sum + b[i][j]
print (sum)
# sum the diagonals of a matrix
def sum_diagonals (b):
# sums diagonal from upper left to lower right
sum = 0
for i in range (len(b)):
sum = sum + b[i][i]
print (sum)
# switches the rows for the columns in a matrix
def transpose (b):
c = []
num_cols = len (b[0])
for j in range (num_cols):
a = []
for i in range (len(b)):
a.append (b[i][j])
c.append(a)
return c
main():
b = [[8, 2, 3], [5, 6, 1], [7, 4, 9]]
c = reverse_rows (b)
print (c)
c = reverse_cols (b)
print (c)
main()