Skip to content

Commit ab221c0

Browse files
committed
Update cachematrix.R
Programming Assignment2 Submission coursera.
1 parent 7f657dd commit ab221c0

File tree

1 file changed

+56
-10
lines changed

1 file changed

+56
-10
lines changed

cachematrix.R

+56-10
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,61 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
5-
1+
### makeCacheMatrix(x) sets up a placeholder list for
2+
## the matrix variable x and the inverse matrix INV
3+
##
4+
## cacheSolve(x) returns the inverse INV or the cached INV
5+
## if it already exists in the placeholder list
6+
## see example, below:
7+
##
8+
## Caution: if the values of the matrix 'x' change
9+
## makeCacheMatrix(x) needs to be called with the updated values
10+
##
11+
## ---- START of sample input/output of actual run----
12+
## > A <- matrix(c(1,5,2,-5),2,2)
13+
## > A
14+
## [,1] [,2]
15+
## [1,] 1 2
16+
## [2,] 5 -5
17+
## > Acache <- makeCacheMatrix(A)
18+
## > cacheSolve(Acache)
19+
## [,1] [,2] # the first time
20+
## [1,] 0.3333333 0.13333333 # the inverse is calculated
21+
## [2,] 0.3333333 -0.06666667
22+
## > cacheSolve(Acache)
23+
## getting cached data # subsequent calls
24+
## [,1] [,2] # return cached data
25+
## [1,] 0.3333333 0.13333333
26+
## [2,] 0.3333333 -0.06666667
27+
## >
28+
## ---- END of sample input/output of actual run----
29+
##
30+
## makeCacheMatrix(x) sets up a placeholder list for
31+
## the matrix variable x and the inverse matrix INV
632
makeCacheMatrix <- function(x = matrix()) {
7-
33+
INV <- NULL
34+
set <- function(y) {
35+
x <<- y
36+
INV <<- NULL
37+
}
38+
get <- function() x
39+
setinverse <- function(inverse) INV <<- inverse
40+
getinverse <- function() INV
41+
list(set = set, get = get,
42+
setinverse = setinverse,
43+
getinverse = getinverse)
844
}
9-
10-
11-
## Write a short comment describing this function
12-
45+
##
46+
## cacheSolve(x) computes the inverse of the special
47+
## "matrix" list returned by `makeCacheMatrix` above. If the inverse has
48+
## already been calculated, then
49+
## `cacheSolve` retrieves the inverse from the cache
1350
cacheSolve <- function(x, ...) {
1451
## Return a matrix that is the inverse of 'x'
52+
INV <- x$getinverse()
53+
if(!is.null(INV)) {
54+
message("getting cached data")
55+
return(INV)
56+
}
57+
data <- x$get()
58+
INV <- solve(data, ...)
59+
x$setinverse(INV)
60+
INV
1561
}

0 commit comments

Comments
 (0)