Skip to content

Commit 45544cc

Browse files
RachelBunderRachelBunder
authored andcommitted
Completed the cache inverse matrix assignment
1 parent 7f657dd commit 45544cc

File tree

1 file changed

+33
-7
lines changed

1 file changed

+33
-7
lines changed

cachematrix.R

Lines changed: 33 additions & 7 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+
## Created by R. Bunder, 2015-01-18
2+
## Two functions: makeCacheMatrix which returns a list with cached elements for calculating the matrix inverse, and cacheSolve which sets the cached inverse (and returns the inverse)
33

4-
## Write a short comment describing this function
5-
6-
makeCacheMatrix <- function(x = matrix()) {
74

5+
## This functions takes a matrix, x, and returns a list contatining functions which for getting the inverse (getinverse), setting the inverse (setInverse), getting the matrix (get) and setting a new matrix (set) which additional optional arguments are also passed into
6+
makeCacheMatrix <- function(x = matrix())
7+
{
8+
inverse = NULL
9+
set <- function(newMatrix){ #when setting a new matrix, set the cached inverse to NULL
10+
x <<- newMatrix
11+
inverse <<- NULL
12+
}
13+
14+
get <- function() x
15+
16+
setInverse <- function(newInverse) newInverse <<- inverse
17+
18+
getInverse <- function() inverse
19+
20+
21+
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
22+
823
}
924

1025

11-
## Write a short comment describing this function
12-
26+
## This function finds the inverse of a cacheMatrix, X, sets the inverse and returns the inverse. The inverse is calcualted using the solve command
1327
cacheSolve <- function(x, ...) {
1428
## Return a matrix that is the inverse of 'x'
29+
inverseCache <- x$getInverse()
30+
if(!is.null(inverseCache)) #If there is already an inverse calculated, return that
31+
{
32+
message("Getting cache data")
33+
return(inverseCache)
34+
}
35+
36+
matrix <- x$get()
37+
inverse <- solve(matrix, ...) #calculating the inverse
38+
x$setInverse(inverse)
39+
40+
inverse
1541
}

0 commit comments

Comments
 (0)