From cf4f02a5a68e47d12041f219adbf404ad9d791c6 Mon Sep 17 00:00:00 2001 From: Fabian Linzberger Date: Fri, 18 Apr 2014 12:16:36 +0200 Subject: [PATCH] add comments and implementation for makeCacheMatrix and cacheSolve functions --- cachematrix.R | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..ae981055253 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,35 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## solution to Assignment: Caching the Inverse of a Matrix +## creates a wrapper object around a matrix that can optionally store +## its inverse. exposes setters and getters for both. invalidates +## cache on set. makeCacheMatrix <- function(x = matrix()) { - + inverse <- NULL + set <- function(y) { + x <<- y + inverse <<- NULL + } + get <- function() x + setinv <- function(inv) inverse <<- inv + getinv <- function() inverse + list(set = set, get = get, setinv = setinv, getinv = getinv) } -## Write a short comment describing this function - -cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' +## computes the inverse of a matrix with caching. +## expects a wrapped matrix as returned from makeCacheMatrix. first +## checks cache in the object passed in for the presence of the result +## of a previous run. if found returns that, otherwise computes the +## result and then stores it in the cache as well as returning it to +## the caller +cacheSolve <- function(x) { + inverse <- x$getinv() + if(!is.null(inverse)) { + message("getting cached data") + return(inverse) + } + data <- x$get() + inverse <- solve(data) + x$setinv(inverse) + inverse }