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/ProgAss2.Rproj b/ProgAss2.Rproj new file mode 100644 index 00000000000..8e3c2ebc99e --- /dev/null +++ b/ProgAss2.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..d8bedeebd22 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,41 @@ -## Put comments here that give an overall description of what your -## functions do +## makeCacheMatrix is very much similar to the makeVector function provided +## the difference is that x is the matrix and im is the inverse -## Write a short comment describing this function +## cacheSolve is similar to cachemean function +## the difference is that x is the matrix and im is the inverse which is computed +## by using the solve() function +## im (the inverse matrix) is assumed as NULL +## inside we have get, set as getter and setter of the matrix +## we also have getinverse, setinverse which acts as getter and setter of the inverse makeCacheMatrix <- function(x = matrix()) { - + im <- NULL + set <- function(y) { + x <<- y + im <<- NULL + } + get <- function() x + setinverse <- function(inverse) im <<- inverse + getinverse <- function() im + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function +## im (the inverse matrix) is first initialized by running getinverse on the matrix x +## if there is cached inverse, we will immediately return it +## otherwise, we will use solve() to calciulate and then set it back to the matrix x cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + im <- x$getinverse() + if(!is.null(im)) { + message("getting cached data") + return(im) + } + the_matrix <- x$get() + im <- solve(the_matrix, ...) + x$setinverse(im) + im }