Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f775ca7

Browse files
committed
Update cachematrix.R
1 parent e4eed41 commit f775ca7

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

cachematrix.R

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,43 @@
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.
39

4-
## Write a short comment describing this function
10+
## This function creates a special "matrix" object that can cache its inverse.
511

612
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)
824
}
925

1026

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.
1231

1332
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
1543
}

0 commit comments

Comments
 (0)