# the matrix function
args(matrix)
# define a matrix
A <- matrix(1:6, 2, 3)
Copyright By PowCoder代写 加微信 powcoder
# Fill a matrix by row:
A <- matrix(1:6, 2, 3, byrow = TRUE)
# Dimensions
dimnames(A) # names of dimensions
dimnames(A) <- list(c("row1", "row2"), c("col1", "col2", "col3"))
# Subsetting elements of a matrix
A[1, 2] # by position or index
A["row1", "col2"] # by names
A[1, ] # extract first row
A[, 2] # extract second column
dim(x) # no dimensions
names(x) <- c("x1", "x2", "x3")
x <- as.matrix(x) # converting vector to matrix
x <- matrix(x, nrow = 1) # creates a matrix with 1 row instead of 1 column
# Transpose of a matrix\
t(A) # transpose function
t(x) # 1. x is converted into a matrix with 1 column 2. transposed into matrix with 1 row
# Symmetric Matrix
S <- matrix(c(1, 2, 2, 1), 2, 2)
t(S) # transpose is the same as the original
S == t(S) # comparison
# Basic Matrix Operations
A <- matrix(c(4, 9, 2, 1), 2, 2)
B <- matrix(c(2, 0, 0, 7), 2, 2)
A + B # Matrix Addition
A - B # Matrix Subtraction
2 * A # Scalar multiplication
A * B # element-wise multiplication
A %*% B # matrix multiplication
C <- matrix(1:6, 2, 3)
A %*% C # This works
C %*% A # This shouldn't work
C * A # This doesn't work either
# Special matrices
I <- diag(2) # 2x2 identity matrix
I %*% A # Result is A
A %*% I # Result is A
A %*% B == B %*% A # Matrix multiplication is not commutative
# Another use of the diag() function
D <- diag(c(4, 8, 9, 17))
# Matrix Inverse
A.inv <- solve(A) # Calculates the matrix inverse if possible
A.inv %*% A # gives the identity matrix
# When is matrix inverse not possible?
F <- matrix(c(1, 1, 2, 2), 2, 2)
solve(F) # inverse doesn't exist
# Solving systems of linear equations
curve(1-x, 0, 1, ylab='y') # Shortcut for the following 3 lines:
x <- seq(0, 1, length = 100)
plot(x, y, type = 'l')
abline(a = -1, b = 2, col = 'blue')
abline(h = 0.4, col = 'red') # for adding horizontal lines
abline(v = 0.2, col = 'cornflowerblue' ) # for adding vertical lines
# 1. y = 1 - x => x + y = 1
# 2. y = -1 + 2x => 2x – y = 1
A <- matrix(c(1, 1, 2, -1), 2, 2, byrow = TRUE)
b <- c(1, 1)
# A z = b => z = inv(A) * b
solve(A) %*% b # point of intersection of the two lines: (2/3, 1,3)
# Summation using matrix algebra
one <- rep(1, 3) # repeats 1 three times
sum(x) # summing elements of a vector
x %*% one # also called the dot product of two vectors
# sum of squares
sum(x^2) # squaring each element of x and summing
x %*% x # same result
x %*% y # dot product of x & y
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com