Lesson 6 of 18
Matrix Operations
Matrix Operations
Matrices support element-wise operations and transpose.
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
# Element-wise addition
add = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
print(add) # [[6, 8], [10, 12]]
# Scalar multiplication
scaled = [[3 * A[i][j] for j in range(len(A[0]))] for i in range(len(A))]
print(scaled) # [[3, 6], [9, 12]]
Transpose
The transpose flips a matrix along its diagonal — rows become columns:
A = [[1, 2, 3],
[4, 5, 6]]
AT = [[A[i][j] for i in range(len(A))] for j in range(len(A[0]))]
print(AT)
# [[1, 4], [2, 5], [3, 6]]
# rows: len(AT) = 3, cols: len(AT[0]) = 2
Symmetric Matrices
A matrix is symmetric if . Covariance matrices and Gram matrices are always symmetric.
Your Task
Implement transpose(A) that returns the transpose of a matrix as a list of lists.
Pyodide loading...
Loading...
Click "Run" to execute your code.