-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
# See README.md for instructions on running the code and output from it | ||
# The assignment states that running the code is not part of the grading | ||
# but I have the instructions anyway. | ||
|
||
# makeCacheMatrix is a function that returns a list of functions | ||
# Its puspose is to store a martix and a cached value of the inverse of the | ||
# matrix. Contains the following functions: | ||
# * setMatrix set the value of a matrix | ||
# * getMatrix get the value of a matrix | ||
# * cacheInverse get the cahced value (inverse of the matrix) | ||
# * getInverse get the cahced value (inverse of the matrix) | ||
# | ||
# Notes: | ||
# not sure how the "x = numeric()" part works in the argument list of the | ||
# function, but it seems to be creating a variable "x" that is not reachable | ||
# from the global environment, but is available in the environment of the | ||
# makeCacheMatrix function | ||
makeCacheMatrix <- function(x = numeric()) { | ||
|
||
# holds the cached value or NULL if nothing is cached | ||
# initially nothing is cached so set it to NULL | ||
cache <- NULL | ||
|
||
# store a matrix | ||
setMatrix <- function(newValue) { | ||
x <<- newValue | ||
# since the matrix is assigned a new value, flush the cache | ||
cache <<- NULL | ||
} | ||
|
||
# returns the stored matrix | ||
getMatrix <- function() { | ||
x | ||
} | ||
|
||
# cache the given argument | ||
cacheInverse <- function(solve) { | ||
cache <<- solve | ||
} | ||
|
||
# get the cached value | ||
getInverse <- function() { | ||
cache | ||
} | ||
|
||
# return a list. Each named element of the list is a function | ||
list(setMatrix = setMatrix, getMatrix = getMatrix, cacheInverse = cacheInverse, getInverse = getInverse) | ||
} | ||
|
||
|
||
# The following function calculates the inverse of a "special" matrix created with | ||
# makeCacheMatrix | ||
cacheSolve <- function(y, ...) { | ||
# get the cached value | ||
inverse <- y$getInverse() | ||
# if a cached value exists return it | ||
if(!is.null(inverse)) { | ||
message("getting cached data") | ||
return(inverse) | ||
} | ||
# otherwise get the matrix, caclulate the inverse and store it in | ||
# the cache | ||
data <- y$getMatrix() | ||
inverse <- solve(data) | ||
y$cacheInverse(inverse) | ||
|
||
# return the inverse | ||
inverse | ||
} |