From f91158da123a75cbcf3b6c4165e3d156a18e2dae Mon Sep 17 00:00:00 2001 From: "Cody A. Ray" Date: Sun, 25 Jan 2015 18:28:57 -0600 Subject: [PATCH] Complete the makeCacheMatrix and cacheSolve methods --- cachematrix.R | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..9843be17d37 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 +## Computes and caches the inverse of a square matrix. +## +## Two methods are exposed: +## makeCacheMatrix creates or wraps a matrix to cache its inverse +## cacheSolve returns the cached inverse if available, or computes and caches it otherwise. +## Creates or wraps a matrix to cache its inverse makeCacheMatrix <- function(x = matrix()) { - + i <- NULL + set <- function(y) { + x <<- y + i <<- NULL + } + get <- function() x + setinverse <- function(inverse) i <<- inverse + getinverse <- function() i + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function - +## Returns the cached inverse if available, or computes and caches it otherwise. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' -} + inverse <- x$getinverse() + if(!is.null(inverse)) { + message("getting cached data") + return(inverse) + } + data <- x$get() + inverse <- solve(data, ...) + x$setinverse(inverse) + inverse +} \ No newline at end of file