diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000000..7ef3ead157a --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.Rproj.user +.Rhistory +.RData +.Ruserdata +.positai 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..360a138b5f5 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,39 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## This function creates a matrix that caches the value of its inverse makeCacheMatrix <- function(x = matrix()) { + matrix_inverse <- NULL #sets inverse to be null until calculated + + #to set the matrix + set <- function(y) { + x <<- y + matrix_inverse <<- NULL + } + #to get the matrix inverse from this function + get <- function() x + setmatrix <- function(solve) matrix_inverse <<- solve + getmatrix <- function() matrix_inverse + list(set = set, get = get, + setmatrix = setmatrix, + getmatrix = getmatrix) } -## Write a short comment describing this function +## to solve for the inverse, and retrieve cached inverse from 'makeCacheMatrix()' when called if it has already been calculated cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + matrix_inverse <- x$getmatrix() #to get the matrix inverse from the first function + if(!is.null(matrix_inverse)) { + message("getting cached data") #to print this message when retrieving cached data if already calculated + return(matrix_inverse) #retrieve cached data if already calculated + } + data <- x$get() #to get initialized matrix + matrix_inverse <- solve(data, ...) #solve for inverse + x$setmatrix(matrix_inverse) #set inverse as new output value + matrix_inverse #return the inverse } + +my_matrix <- makeCacheMatrix(matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2)) #to initialize matrix for testing +cacheSolve(my_matrix) #first function run to calculate matrix inverse +cacheSolve(my_matrix) #to see if inversion was gotten from cache this time and not recalculated +my_matrix$getmatrix() #to see if cache was stored in 'getmatrix()'