From 7657463e69c7e98e08beeafa666a401ef570f831 Mon Sep 17 00:00:00 2001 From: "Nils o. Janus" Date: Sun, 12 Feb 2017 09:49:05 +0100 Subject: [PATCH] filled both method stubs "makeCacheMatrix" and "cacheSolve" with code and comments; verified that caching works via the following timestamping test: now <- Sys.time(); mat <- makeCacheMatrix(h10); cacheSolve(mat); diff <- Sys.time() - now; diff now <- Sys.time(); mat$getinv(); diff <- Sys.time() - now; diff where h10 is the 10x10 hilbert matrix --- cachematrix.R | 45 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..e5d0c2dafb3 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,52 @@ -## Put comments here that give an overall description of what your -## functions do +## These two functions allow for caching the inverse of a matrix, to save +## compuation time for this CPU intensive operation +## For this, two functions are defined: +## - makeCacheMatrix: allows for caching a matrix and its inverse +## - cacheSolve: computing and storing the inverse -## Write a short comment describing this function +## allows for caching a matrix and its inverse makeCacheMatrix <- function(x = matrix()) { + i <- NULL + ## making sure that if a new matrix is set, we store its value + ## and reset our inverse (since we haven't calculated it yet) + set <- function(y) { + x <<- y + i <<- NULL + } + ## return the original base matrix + get <- function() x + + ## set new value for the inverse + setinv <- function(mat) i <<- mat + + ## return value of the inverse + getinv <- function() i + list(set = set, get = get, setinv = setinv, getinv = getinv) } -## Write a short comment describing this function +## This is the function to which we pass the function (which is really a list) +## "makeCacheMatrix" and compute and store the inverse cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' + i <- x$getinv() + + ## in case we already know the inverse, we skip recomputing it and return the cached value + if(!is.null(i)) { + message("getting cached inverse") + return(i) + } + + ## getting our base matrix ... + data <- x$get() + + ## ... passing it to the R solver (making sure to catch any errors) ... + i <- try(solve(data, ...)) + + ## ... and storing and displaying the result + x$setinv(i) + i }