From 4f838e927308531320d6f393b42bbceafc611f5d Mon Sep 17 00:00:00 2001 From: andraspap Date: Tue, 15 Apr 2014 22:03:56 -0400 Subject: [PATCH] Assignment done. --- cachematrix.R | 52 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..4b9abc3d132 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,55 @@ ## Put comments here that give an overall description of what your ## functions do -## Write a short comment describing this function - +## Create a special matrix that can store its inverse as well +## to avoid possible repeats of long computations makeCacheMatrix <- function(x = matrix()) { - + # Initialize the inverse to NULL + invX <- NULL + + # Setter function for the matrix x + set <- function(y) { + # Set the matrix (in the parent i.e. makeCacheMatrix environment) + x <<- y + # Reset the inverse to NULL (out of sync from x) + invX <<- NULL + } + + # Getter for the matrix itself + get <- function() x + + # Setter for the inverse + setinv <- function(inv) invX <<- inv #in the parent i.e. makeCacheMatrix environment + + # Getter for the inverse + getinv <- function() invX + + # List the function withint this function + list(set = set, get = get, + setinv = setinv, + getinv = getinv) } -## Write a short comment describing this function - +## Return the inverse of a special matrix if type makeCacheMatrix cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + inv <- x$getinv() + + + if(!is.null(inv)) { + message("getting cached data") + return(inv) + } + + # Not chaced so calculate the inverse + # Get the data + data <- x$get() + # Solve + inv <- solve(data) + # Set the inverse on the special matrix + x$setinv(inv) + + # Return the inverse + inv }