Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 496432f

Browse files
committed
Implement matrix caching functions
Implements: makeCacheMatrix cacheSolve
1 parent 7f657dd commit 496432f

File tree

1 file changed

+32
-6
lines changed

1 file changed

+32
-6
lines changed

cachematrix.R

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,41 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## This function creates a list comprising of 4 functions:
32

4-
## Write a short comment describing this function
3+
## set <- sets matrix x in the makeCacheMatrix context
4+
## and clears the previous cached inverse (m)
55

6-
makeCacheMatrix <- function(x = matrix()) {
6+
## get <- gets matrix x in the makeCacheMatrix context
77

8-
}
8+
## setinverse <- sets cached inverse m in the makeCacheMatrix context
9+
10+
## getinverse <- cached inverse m in the makeCacheMatrix context
911

12+
makeCacheMatrix <- function(x = matrix()) {
13+
m <- NULL
14+
set <- function(y) {
15+
x <<- y
16+
m <<- NULL
17+
}
18+
get <- function() x
19+
setinverse <- function(solve) m <<- solve
20+
getinverse <- function() m
21+
list(set = set, get = get,
22+
setinverse = setinverse,
23+
getinverse = getinverse)
24+
}
1025

11-
## Write a short comment describing this function
26+
## This function checks whether the inverse was already calculated and cached
27+
## If that's the case, just returns the cached value
28+
## Otherwise, calculates the inverse via solve function, caches and returns it
1229

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

0 commit comments

Comments
 (0)