Skip to content

Commit ddc8051

Browse files
author
Alexey Babich
committed
Basic implementation of cacheable matrix and inverse calculation
1 parent 7f657dd commit ddc8051

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

cachematrix.R

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,33 @@
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+
## The pair of functions below creates a cacheable matrix object
2+
## and allows to store inverse matrix calculation result in memory to reuse
3+
## solve() is used for calculation
54

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

1020

11-
## Write a short comment describing this function
12-
21+
## Returns inverse of matrix object created using `makeCacheMatrix`
1322
cacheSolve <- function(x, ...) {
1423
## Return a matrix that is the inverse of 'x'
24+
inv_m <- x$getinverse()
25+
if(!is.null(inv_m)) {
26+
# message("getting cached data")
27+
return(inv_m)
28+
}
29+
data <- x$get()
30+
inv_m <- solve(data, ...) # solve() is the function to get inverse of a square matrix
31+
x$setinverse(inv_m)
32+
inv_m
1533
}

0 commit comments

Comments
 (0)