8000 Assignment #2 · ua-umka/ProgrammingAssignment2@6ed2784 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6ed2784

Browse files
committed
Assignment rdpeng#2
1 parent 9b22d21 commit 6ed2784

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
lines changed

cachematrix.R

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,40 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Matrix inversion is usually a costly computation and there may be some benefit
2+
## to caching the inverse of a matrix rather than compute it repeatedly.
3+
## Here presented a pair of functions that cache the inverse of a matrix.
34

4-
## Write a short comment describing this function
5+
## "makeCacheMatrix" function creates a special "matrix" object that can cache its inverse.
6+
## This "matrix" is really a list containing a function to:
7+
## set the value of the matrix
8+
## get the value of the matrix
9+
## set the value of the inverse matrix
10+
## get the value of the inverse matrix
511

612
makeCacheMatrix <- function(x = matrix()) {
7-
13+
inv <- NULL
14+
set <- function(y) { ## set the value of the matrix
15+
x <<- y
16+
inv <<- NULL
17+
}
18+
get <- function() x ## get the value of the matrix
19+
setinv <- function(solution) inv <<- solution ## set the value of the inverse matrix
20+
getinv <- function() inv ## get the value of the inverse matrix
21+
list(set = set, get = get, setinv = setinv, getinv = getinv) ## return the list
822
}
923

1024

11-
## Write a short comment describing this function
25+
## The following function calculates the inverse matrix of the special "matrix" created with the above function.
26+
## However, it first checks to see if the inverse matrix has already been calculated.
27+
## If so, it gets the result from the cache and skips the computation.
28+
## Otherwise, it calculates the inverse of the matrix and sets the value in the cache via the setinv function.
1229

1330
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
31+
inv <- x$getinv() # query the x matrix's cache
32+
if (!is.null(inv)) { # if there is already a value in the cache
33+
message("getting cached data")
34+
return(inv) # just return the cached value, no computation needed
35+
}
36+
data <- x$get() # if there's no value in the cache
37+
inv <- solve(data, ...) # compute inverse matrix
38+
x$setinv(inv) # save the result back to x's cache
39+
inv # return the result
1540
}

0 commit comments

Comments
 (0)
0