Skip to content

Commit 435531b

Browse files
committed
Implemented makeCacheMatrix and cacheSolve.
1 parent 7f657dd commit 435531b

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

cachematrix.R

Lines changed: 30 additions & 5 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+
## Contains a pair of functions to cache an inverse matrix. The value
2+
## from makeCacheMatrix should be the first parameter to cacheSolve.
33

4-
## Write a short comment describing this function
4+
## Creates a matrix structure whose inverse matrix can be cached.
5+
## The resulting list has the following structure:
6+
## - set: sets the original matrix to be solved.
7+
## - get: gets the original matrix.
8+
## - setinverse: sets the inverse matrix of the original matrix.
9+
## - getinverse: gets the inverse matrix of the original matrix.
510

611
makeCacheMatrix <- function(x = matrix()) {
7-
12+
solved <- NULL
13+
set <- function(y) {
14+
x <<- y
15+
solved <<- NULL
16+
}
17+
get <- function() x
18+
setinverse <- function(inverse) solved <<- inverse
19+
getinverse <- function() solved
20+
list(set = set, get = get,
21+
setinverse = setinverse,
22+
getinverse = getinverse)
823
}
924

1025

11-
## Write a short comment describing this function
26+
## Returns the inverse of a matrix if it has been solved. Otherwise, it
27+
## will solve the inverse matrix and cache it for future use.
1228

1329
cacheSolve <- function(x, ...) {
1430
## Return a matrix that is the inverse of 'x'
31+
i <- x$getinverse()
32+
if(!is.null(i)) {
33+
message("getting cached data")
34+
return(i)
35+
}
36+
data <- x$get()
37+
i <- solve(data, ...)
38+
x$setinverse(i)
39+
i
1540
}

0 commit comments

Comments
 (0)