File tree Expand file tree Collapse file tree 1 file changed +34
-6
lines changed Expand file tree Collapse file tree 1 file changed +34
-6
lines changed Original file line number Diff line number Diff line change 1
- # # Put comments here that give an overall description of what your
2
- # # functions do
1
+ # # Assignment: Caching the Inverse of a Matrix
2
+ # # (Programming Assignment 2 for R Programming on Coursera)
3
+ # #
4
+ # # Matrix inversion is usually a costly computation and their may be some
5
+ # # benefit to caching the inverse of a matrix rather than compute it repeatedly
6
+ # # (there are also alternatives to matrix inversion that we will not discuss
7
+ # # here). Your assignment is to write a pair of functions that cache the
8
+ # # inverse of a matrix.
3
9
4
- # # Write a short comment describing this function
10
+ # # This function creates a special "matrix" object that can cache its inverse.
5
11
6
12
makeCacheMatrix <- function (x = matrix ()) {
7
-
13
+ inv_x <- NULL
14
+ set <- function (y ) {
15
+ x <<- y
16
+ inv_x <<- NULL
17
+ }
18
+ get <- function () x
19
+ setInv <- function (inv_mat ) inv_x <<- inv_mat
20
+ getInv <- function () inv_x
21
+ list (set = set , get = get ,
22
+ setInv = setInv ,
23
+ getInv = getInv )
8
24
}
9
25
10
26
11
- # # Write a short comment describing this function
27
+ # # This function computes the inverse of the special "matrix" returned by
28
+ # # makeCacheMatrix above. If the inverse has already been calculated (and the
29
+ # # matrix has not changed), then the cachesolve should retrieve the inverse
30
+ # # from the cache.
12
31
13
32
cacheSolve <- function (x , ... ) {
14
- # # Return a matrix that is the inverse of 'x'
33
+ # # Return a matrix that is the inverse of 'x'
34
+ inv_x <- x $ getInv()
35
+ if (! is.null(inv_x )) {
36
+ message(' getting cached inverse matrix' )
37
+ return (inv_x )
38
+ }
39
+ data <- x $ get()
40
+ inv_x <- solve(data , ... )
41
+ x $ setInv(inv_x )
42
+ inv_x
15
43
}
You can’t perform that action at this time.
0 commit comments