Introduction
Matrix arithmetic helps you do math with tables of numbers easily, like adding, subtracting, or multiplying grids of values.
A + B # Add two matrices A - B # Subtract matrix B from A A %*% B # Multiply two matrices A * B # Multiply matrices element-wise solve(A) # Find inverse of matrix A
A <- matrix(c(1,2,3,4), nrow=2) B <- matrix(c(5,6,7,8), nrow=2) A + B
A <- matrix(c(1,2,3,4), nrow=2) B <- matrix(c(5,6,7,8), nrow=2) A %*% B
A <- matrix(c(1,2,3,4), nrow=2) A * 2
A <- matrix(c(1, 2, 3, 4), nrow=2) B <- matrix(c(5, 6, 7, 8), nrow=2) # Add matrices sum_matrix <- A + B # Multiply matrices prod_matrix <- A %*% B print("Sum of matrices:") print(sum_matrix) print("Product of matrices:") print(prod_matrix)
%*% do when applied between two matrices?+ and - perform element-wise addition and subtraction respectively, while %*% is used for matrix multiplication.%*%%*% multiplies matrices according to linear algebra rules, not element-wise.%*% = matrix multiplication [OK]matrix() takes a vector of values and parameters nrow and ncol to specify dimensions.c(1, 2, 3, 4) and named arguments nrow=2, ncol=2. matrix(1, 2, 3, 4, nrow=2, ncol=2) has wrong argument format. matrix(c(1, 2, 3, 4), rows=2, cols=2) uses invalid argument names. matrix(1, 2, 3, 4, 2, 2) uses positional arguments without the vector wrapper.m1 <- matrix(c(1, 2, 3, 4), nrow=2, ncol=2, byrow=TRUE) m2 <- matrix(c(5, 6, 7, 8), nrow=2, ncol=2, byrow=TRUE) m3 <- m1 + m2 print(m3)
+ between matrices adds corresponding elements: (1+5), (2+6), (3+7), (4+8).m1 <- matrix(c(1, 2, 3, 4), nrow=2) m2 <- matrix(c(5, 6, 7), nrow=3) m3 <- m1 %*% m2 print(m3)
m1 <- matrix(c(1, 0, 2, -1), nrow=2) m2 <- matrix(c(3, 1, 4, 2), nrow=2)
m1 %*% m2 and then subtract the identity matrix of size 2. Which code correctly does this?%*% to multiply m1 and m2 correctly.diag(2) to create a 2x2 identity matrix and subtract it from the product.Pass the test and this pattern moves unknown