Skip to content

Commit 05cf417

Browse files
committed
Updating the code from README to use the solve() function
1 parent 7f657dd commit 05cf417

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

cachematrix.R

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,38 @@
11
## Put comments here that give an overall description of what your
22
## functions do
33

4-
## Write a short comment describing this function
4+
## This function creates a special "matrix" object
5+
## that can cache its inverse.
56

67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
matrix <- NULL
9+
set <- function(y) {
10+
x <<- y ## search through parent environment first for a value for y and assign to x
11+
inverse <<- NULL ## set the inverse to null, unless it already exists
12+
}
13+
get <- function() x
14+
setinverse <- function(inverse) x <<- inverse #set the inverse value
15+
getinverse <- function() x #get the inverse value
16+
list(set = set, get = get,
17+
setinverse = setinverse,
18+
getinverse = getinverse)
19+
}
820
}
921

10-
11-
## Write a short comment describing this function
12-
22+
## This function computes the inverse of the special
23+
## "matrix" returned by `makeCacheMatrix` above.
24+
## Computing the inverse of a square matrix can be done with the `solve`
25+
## function in R.
26+
## n is the inverted matrix
1327
cacheSolve <- function(x, ...) {
1428
## Return a matrix that is the inverse of 'x'
15-
}
29+
n <- x$getinverse()
30+
if(!is.null(n)) {
31+
message("getting cached data")
32+
return(n) #return the cached inverted matrix if it already exists
33+
}
34+
data <- x$get() #if we don't have a in existing inverted matrix, create one
35+
n <- solve(data, ...)
36+
x$setinverse(n)
37+
n
38+
}

0 commit comments

Comments
 (0)