diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000000..807ea251739 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.Rproj.user +.Rhistory +.RData diff --git a/ProgrammingAssignment2.Rproj b/ProgrammingAssignment2.Rproj new file mode 100644 index 00000000000..8e3c2ebc99e --- /dev/null +++ b/ProgrammingAssignment2.Rproj @@ -0,0 +1,13 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 2 +Encoding: UTF-8 + +RnwWeave: Sweave +LaTeX: pdfLaTeX diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..5e40648eeeb 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,47 @@ -## Put comments here that give an overall description of what your -## functions do +## The following functions allow for the creation of a matrix where the invers +## is cached after it has been calculated. This prevents the re-execution +## of a rather expensive operation. -## Write a short comment describing this function - -makeCacheMatrix <- function(x = matrix()) { +## makeCacheMatrix creates a 'special' matrix object that stores the +## matrix as well as its inverce. Use this matrix with cacheSolve() +makeCacheMatrix <- function(m.orig = matrix()) { + m.result <- NULL #when created the result is not available + set <- function(m.set) { + m.orig <<- m.set #save the new matrix + m.result <<- NULL #clear the result + } + + get <- function() m.orig #return the original + + setresult <- function(result) m.result <<- result #save a result matrix + + getresult <- function() m.result #return the result matrix + + list(set = set, get = get, + setresult = setresult, + getresult = getresult) } -## Write a short comment describing this function +## cacheSolve finds the inverse of the matrix created by makeCacheMatrix(). +## The inverse of the matrix is only calculated once. On subsequent calls, the +## cached result is used. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + mcache <- NULL #Cached matrix is initially null + + m <- x$getresult() #Get the cached matrix and check if it exists + if(!is.null(m)){ + message("Using cached data") + return(m) #Use and return the cached matrix if found + } + + # Cached result was not found... Calculate + data <- x$get() #Get the initial matrix + result <- solve(data, ...) #Solve it + x$setresult(result) #Cache it + result #Return it } + +#done