Skip to content

Commit 98f1946

Browse files
committed
Updated cachematrix.R with implementation of functions makeCacheMatrix and cacheSolve
1 parent 7f657dd commit 98f1946

File tree

1 file changed

+41
-9
lines changed

1 file changed

+41
-9
lines changed

cachematrix.R

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,47 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
# Coursera, R Programming(rprog-010), January 2015
2+
# Cache the inverse of a matrix
3+
# Matrix inversion is usually a costly computation and it makes sense
4+
# to cache the inverse of a matrix rather than compute it repeatedly
5+
# These two functions calculate and cache the inverse of a matrix.
36

4-
## Write a short comment describing this function
7+
## Example of usage
8+
## m <- matrix(c(4, 3, 3, 2), nrow = 2)
9+
## store the initial matrix in cached matrix object
10+
## m_cached <- makeCacheMatrix(m)
11+
## first call will solve the inverse and cache it
12+
## cacheSolve(m_cashed)
13+
## second call will return the cached value
14+
## cacheSolve(m_cashed)
515

16+
# This function creates an interface to access(get) and cache(set)
17+
# the contents of a matrix and the inverse of original matrix.
618
makeCacheMatrix <- function(x = matrix()) {
7-
19+
inverse <- NULL
20+
set <- function(y) {
21+
x <<- y
22+
inverse <<- NULL
23+
}
24+
get <- function() x
25+
set_inverse <- function(inv) inverse <<- inv
26+
get_inverse <- function() inverse
27+
list(set = set, get = get,
28+
set_inverse = set_inverse,
29+
get_inverse = get_inverse)
830
}
9-
10-
11-
## Write a short comment describing this function
12-
31+
# This function computes the inverse of the special "matrix"
32+
# returned by makeCacheMatrix above.
1333
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
34+
## Return a matrix that is the inv_matrix of 'x'
35+
inverse <- x$get_inverse()
36+
# check if inverse matrix was already calculated and
37+
# retrieve the content from the cache.
38+
if(!is.null(inverse)) {
39+
message("getting cached data")
40+
return(inverse)
41+
}
42+
# else calculate the inverse matrix
43+
data <- x$get()
44+
inverse <- solve(data, ...)
45+
x$set_inverse(inverse)
46+
inverse
1547
}

0 commit comments

Comments
 (0)