Skip to content

Commit f774746

Browse files
author
Annie
committed
cache matrix and its inverse
1 parent 7f657dd commit f774746

File tree

1 file changed

+63
-7
lines changed

1 file changed

+63
-7
lines changed

cachematrix.R

100644100755
Lines changed: 63 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,71 @@
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+
## This progrom computes a matrix inverse
2+
## For this assignment, assume that the matrix supplied is always invertible
3+
##
4+
## The program consists of two functions:
5+
##
6+
## One function returns a matrix inverse either
7+
## from cache or from computation with cache miss
8+
## a computed inverse is cached by design
9+
##
10+
## The other function provides handles to the original matrix and its inverse
11+
## In this function, we can set/get the original matrix
12+
## we can also set/get the matrix inverse
513

14+
## This function creates a special "matrix" object
15+
## that can cache its inverse.
616
makeCacheMatrix <- function(x = matrix()) {
17+
## initialize the invertible matrix to null
18+
b <- NULL
719

8-
}
20+
## populate the original matrix per argument
21+
## and initialize its inverse to null
22+
set <- function(y){
23+
x <<- y
24+
b <<- NULL
25+
}
26+
27+
## fetch the original matrix
28+
get <- function() {
29+
x
30+
}
931

32+
## populate the invertible matrix per argument
33+
setinverse <- function(inverse) {
34+
b <<- inverse
35+
}
1036

11-
## Write a short comment describing this function
37+
## fetch the invertible matrix
38+
getinverse <- function() {
39+
b
40+
}
41+
42+
list(set = set,
43+
get = get,
44+
setinverse = setinverse,
45+
getinverse = getinverse)
46+
}
1247

48+
49+
## This function computes the inverse of the special
50+
## "matrix" returned by `makeCacheMatrix` above. If the inverse has
51+
## already been calculated (and the matrix has not changed), then
52+
## `cacheSolve` should retrieve the inverse from the cache.
1353
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
54+
# fetch matrix inverse from cache
55+
b <- x$getinverse()
56+
57+
# if in cache, return cached inverse
58+
if (!is.null(b)){
59+
message("getting cached data")
60+
return(b)
61+
}
62+
63+
# otherwise, compute the matrix inverse
64+
data <- x$get()
65+
b <- solve(data)
66+
# cache the computed inverse matrix
67+
x$setinverse(b)
68+
69+
## return the computed inverse matrix
70+
b
1571
}

0 commit comments

Comments
 (0)