Skip to content

Commit 476c3bb

Browse files
committed
matrix memoization
1 parent 7f657dd commit 476c3bb

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

cachematrix.R

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,35 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Matrix inverse memoization
32

4-
## Write a short comment describing this function
3+
## Creates a special matrix object which has functions
4+
## for getting, saving the matrix data and its inverse.
55

66
makeCacheMatrix <- function(x = matrix()) {
7-
7+
i <- NULL
8+
set <- function(y) {
9+
x <<- y
10+
i <<- NULL
11+
}
12+
get <- function() x
13+
setinverse <- function(inverse) i <<- inverse
14+
getinverse <- function() i
15+
list(set = set, get = get,
16+
setinverse = setinverse,
17+
getinverse = getinverse)
818
}
919

1020

11-
## Write a short comment describing this function
21+
## Uses the special matrix object created by makeCacheMatrix.
22+
## Returns the inverse of matrix from cache if it was calculated
23+
## before. If not, calculates and saves is to the obect.
1224

1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
i <- x$getinverse()
27+
if(!is.null(i)) {
28+
message("getting cached data")
29+
return(i)
30+
}
31+
data <- x$get()
32+
i <- solve(data, ...)
33+
x$setinverse(i)
34+
i
1535
}

0 commit comments

Comments
 (0)