forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
104 lines (73 loc) · 2.14 KB
/
cachematrix.R
File metadata and controls
104 lines (73 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
## Caching the Inverse of a Matrix
## makeCacheMatrix: This function creates a special
## "matrix" object that can cache its inverse.
## makeCacheMatrix function.
##
## Usage example:
## x <- matrix(1:9, nrow=3, ncol=3)
## m <- makeCacheMatrix(x)
makeCacheMatrix <- function(x = matrix()) {
# Initially set it to NULL
inv_matrix <- NULL
# Set a function
# It sets the matrix itself but not its inverse
set <- function(y) {
x <<- y
inv_matrix <<- NULL
}
# Get the function
# It gets the matrix itself but not its inverse
get <- function() x
# Set the inverse manually
setinverse <- function(inverse) inv_matrix <<- inverse
# Get the inverse
getinverse <- function() inv_matrix
# Encapsulate into a list
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
}
## cacheSolve: This function computes the inverse of the special
## "matrix" returned by makeCacheMatrix function.
##
## If the user tries to use cacheSolve again on the same special
## matrix, then the pre-computed result is returned.
##
cacheSolve <- function(x, ...) {
# Get the current state of the inverse and check if it
# has already been computed
inv_matrix <- x$getinverse()
if(!is.null(inv_matrix)) {
# Return the computed inverse
message("Getting cached matrix")
return(inv_matrix)
}
# Otherwise get the matrix itself
data <- x$get()
# Calculate the inverse
inv_matrix <- solve(data, ...)
# Cache this result in the object
x$setinverse(inv_matrix)
# Return theresult
inv_matrix
}
## Usage example:
## x <- matrix(1:4, nrow=2, ncol=2)
## m <- makeCacheMatrix(x)
## solution_1 <- cacheSolve(m)
## print(solution_1)
##
## solution_1 should return:
##
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
##
##
## solution_2 <- cacheSolve(m)
## This should display a "Getting cached matrix" message
## print(solution_2)
## solution_2 should return
##
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
##