Weekly Project: Matrix Operations
For this week's project, you'll create a set of functions to perform basic matrix operations. This will help reinforce your understanding of 2D arrays and list manipulation.
Your task is to implement the following functions:
print_matrix(matrix): Neatly print a matrix
matrix_addition(matrix1, matrix2): Add two matrices
matrix_scalar_multiply(matrix, scalar): Multiply a matrix by a scalar
matrix_transpose(matrix): Transpose a matrix
Here's a starting template with some test cases:
def print_matrix(matrix):
# Your code here
pass
def matrix_addition(matrix1, matrix2):
# Your code here
pass
def matrix_scalar_multiply(matrix, scalar):
# Your code here
pass
def matrix_transpose(matrix):
# Your code here
pass
# Test matrices
matrix_a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix_b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
# Test your functions
print("Matrix A:")
print_matrix(matrix_a)
print("
Matrix B:")
print_matrix(matrix_b)
print("
Matrix A + B:")
result = matrix_addition(matrix_a, matrix_b)
print_matrix(result)
print("
Matrix A * 2:")
result = matrix_scalar_multiply(matrix_a, 2)
print_matrix(result)
print("
Transpose of Matrix A:")
result = matrix_transpose(matrix_a)
print_matrix(result)
Implement the functions in the code editor below. Make sure to handle potential errors, such as matrices of different sizes for addition. When you're done, run your code to test all the functions.
This project will give you hands-on experience with 2D arrays and help you practice the list manipulation techniques we've covered this week. Good luck!
# Implement your matrix operations here
def print_matrix(matrix):
# Your code here
pass
def matrix_addition(matrix1, matrix2):
# Your code here
pass
def matrix_scalar_multiply(matrix, scalar):
# Your code here
pass
def matrix_transpose(matrix):
# Your code here
pass
# Test matrices
matrix_a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix_b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
# Your test code here