Matrix Arithmetic and Operations
Perform element-wise and matrix multiplication, addition, and subtraction.
Element-wise vs Matrix Operations
R distinguishes between element-wise operations (using +, -, *, /) and true matrix operations (using %*%). Understanding this difference is critical for correct linear algebra.
A <- matrix(c(1,2,3,4), nrow = 2)
B <- matrix(c(5,6,7,8), nrow = 2)
cat('A:
'); print(A)
cat('B:
'); print(B)
# Element-wise multiply
cat('A * B (element-wise):
'); print(A * B)
# Matrix multiply
cat('A %*% B (matrix mult):
'); print(A %*% B)Element-wise Addition and Subtraction
+ and - between two matrices of the same dimensions add or subtract corresponding elements. These are purely element-wise operations.
# Monthly revenue vs target (in thousands)
revenue <- matrix(c(120,135,110,98, 145,160,132,115),
nrow = 2, byrow = TRUE)
target <- matrix(c(130,130,130,130, 150,150,150,150),
nrow = 2, byrow = TRUE)
deviation <- revenue - target
cat('Revenue vs Target deviation:
')
print(deviation)
cat('Above target?:
')
print(revenue >= target)All lessons in this course
- Creating Matrices with matrix()
- Matrix Indexing and Subsetting
- Matrix Arithmetic and Operations
- Transposing and Reshaping Matrices