Skip to content

Commit 5581911

Browse files
committed
submit assignment2
1 parent 7f657dd commit 5581911

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

cachematrix.R

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,42 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## These functions are used to cache the inverse of a matrix.
2+
## The purpose is to avoid the same computations again and again
3+
## of matrix inversions by caching the result.
34

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

12+
# Function `makeCacheMatrix`
613
makeCacheMatrix <- function(x = matrix()) {
7-
14+
inv <- NULL
15+
set <- function(y) {
16+
x <<- y
17+
inv <<- NULL
18+
}
19+
get <- function() x
20+
setInverse <- function(inverse) inv <<- inverse
21+
getInverse <- function() inv
22+
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
823
}
924

1025

11-
## Write a short comment describing this function
26+
## This function computes the inverse of the special "matrix" object created
27+
## by `makeCacheMatrix`. If the inverse has already been calculated and the matrix
28+
## has not changed, it retrieves the cached inverse to save computation time.
29+
## Otherwise, it calculates the inverse and stores it in the cache.
1230

31+
# Function `cacheSolve`
1332
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
33+
inv <- x$getInverse()
34+
if(!is.null(inv)) {
35+
message("getting cached data")
36+
return(inv)
37+
}
38+
data <- x$get()
39+
inv <- solve(data, ...)
40+
x$setInverse(inv)
41+
inv
1542
}

0 commit comments

Comments
 (0)