Skip to content

Commit 5f8e040

Browse files
committed
Adding solution to the code
1 parent a26b252 commit 5f8e040

File tree

1 file changed

+42
-10
lines changed

1 file changed

+42
-10
lines changed

cachematrix.R

Lines changed: 42 additions & 10 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
3-
4-
## Write a short comment describing this function
5-
6-
makeCacheMatrix <- function(x = matrix()) {
1+
## This code provides a cacheable way to
2+
## invert matrices.
73

4+
## This is a object that takes in a matrix
5+
## and provides functions to return that matrix and also
6+
## caches and return the inverse of the matrix
7+
makeCacheMatrix <- function(mat = matrix()) {
8+
inv = NULL
9+
# Set the internal variable mat with supplied matrix
10+
set <- function(y) {
11+
mat <<- y
12+
inv <<- NULL
13+
}
14+
# Return matrix
15+
get <- function() mat
16+
# Set the internal variable inv with the inverse
17+
setinverse <- function(inverse) inv <<- inverse
18+
# Return matrix inverse
19+
getinverse <- function() inv
20+
# Return the list of callable arguments
21+
list(set = set, get = get,
22+
setinverse = setinverse,
23+
getinverse = getinverse)
824
}
925

10-
11-
## Write a short comment describing this function
12-
26+
## This function takes in a makeCacheMatrix object and returns it's inverse
1327
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
28+
# Tries to get a cached copy and return
29+
inverse <- x$getinverse()
30+
if(!is.null(inverse)) {
31+
message("getting cached data")
32+
return(inverse)
33+
}
34+
# If none gets the matrix
35+
data <- x$get()
36+
# Calculates it's inverse
37+
inverse <- solve(data, ...)
38+
# And sets the inverse on the makeCacheMatrix container
39+
x$setinverse(inverse)
40+
inverse
1541
}
42+
mat = matrix(c(4,3,3,2), 2)
43+
print(mat)
44+
cacheMat = makeCacheMatrix(mat)
45+
inverseMat = cacheSolve(cacheMat)
46+
inverseMat = cacheSolve(cacheMat)
47+
print(inverseMat)

0 commit comments

Comments
 (0)