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

Skip to content

Commit 512b005

Browse files
committed
asst 2
1 parent 7f657dd commit 512b005

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

cachematrix.R

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,38 @@
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+
## Create a special object that stores a matrix, and caches
2+
## its inverse.
53

4+
## This function creates an object that provides functions for storing
5+
## and retrieving a matrix (set, get), as well as storing and retrieving
6+
## the matrix's inverse (setinverse, getinverse).
67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
inv <- NULL
9+
set <- function(y) {
10+
x <<- y
11+
inv <<- NULL ## reset the inverse to null
12+
}
13+
get <- function() x
14+
setinverse <- function(inverse) inv <<- inverse
15+
getinverse <- function() inv
16+
list(set = set, get = get,
17+
setinverse = setinverse,
18+
getinverse = getinverse)
819
}
920

1021

11-
## Write a short comment describing this function
12-
22+
## This function return a matrix that is the inverse of the matrix
23+
## stored in x.
24+
## - If there is a cached value, then that value is returned.
25+
## - If a cached value does not exist, then the function calculates
26+
## the inverse, caches it, and returns that value.
1327
cacheSolve <- function(x, ...) {
1428
## Return a matrix that is the inverse of 'x'
29+
inv <- x$getinverse()
30+
if(!is.null(inv)) {
31+
message("getting cached data")
32+
return(inv)
33+
}
34+
data <- x$get()
35+
inv <- solve(data)
36+
x$setinverse(inv)
37+
inv
1538
}

0 commit comments

Comments
 (0)