1
- # # Put comments here that give an overall description of what your
2
- # # functions do
3
-
4
- # # Write a short comment describing this function
1
+ # # cacheSolve and makeCacheMatrix are used to cache matrix inverses, which can be expensive calculations.
2
+ # #
3
+ # # For example,
4
+ # #
5
+ # #> foo <- matrix(data = c(1.4,3,2,-6.7), nrow = 2, ncol = 2) # creates a 2x2 matrix
6
+ # #> x <- makeCacheMatrix(foo) # create a cache matrix
7
+ # #> cacheSolve(x) # cacheSolve the cache matrix, x
8
+ # #[,1] [,2]
9
+ # #[1,] 0.4356307 0.13003901
10
+ # #[2,] 0.1950585 -0.09102731
11
+ # #> cacheSolve(x) # cacheSolve the cache matrix, x. note the "getting cached data" message.
12
+ # #getting cached data
13
+ # #[,1] [,2]
14
+ # #[1,] 0.4356307 0.13003901
15
+ # #[2,] 0.1950585 -0.09102731
16
+ # #
5
17
18
+ # # makeCacheMatrix creates a special “matrix” object that can cache its inverse.
6
19
makeCacheMatrix <- function (x = matrix ()) {
7
-
20
+ m <- NULL
21
+ set <- function (y ) {
22
+ x <<- y
23
+ m <<- NULL
24
+ }
25
+ get <- function () x
26
+ setinv <- function (inv ) m <<- inv
27
+ getinv <- function () m
28
+ list (
29
+ set = set ,
30
+ get = get ,
31
+ setinv = setinv ,
32
+ getinv = getinv
33
+ )
8
34
}
9
35
10
-
11
- # # Write a short comment describing this function
12
-
36
+ # # cacheSolve computes the inverse of the special “matrix” returned by makeCacheMatrix. If a cached inverse cannot be found,
37
+ # # it calculates the inverse, saves the result in the CacheMatrix (x), and returns the result.
13
38
cacheSolve <- function (x , ... ) {
14
- # # Return a matrix that is the inverse of 'x'
15
- }
39
+ # # Return a matrix that is the inverse of 'x'
40
+ m <- x $ getinv()
41
+ if (! is.null(m )) {
42
+ message(" getting cached data" )
43
+ return (m )
44
+ } else {
45
+ data <- x $ get()
46
+ m <- solve(data )
47
+ x $ setinv(m )
48
+ m
49
+ }
50
+ }
0 commit comments