From 64a5da8811a9f754ba1fa0d991f15a491a6db255 Mon Sep 17 00:00:00 2001 From: cstuss Date: Fri, 20 Mar 2015 14:57:58 -0400 Subject: [PATCH] makeCacheMatrix and cacheSolve methods --- cachematrix.R | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..7e931ed1439 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,40 @@ -## Put comments here that give an overall description of what your -## functions do +## A pair of functions that cache the inverse of a matrix -## Write a short comment describing this function +## makeCacheMatrix: This function creates a special "matrix" object that can cache its inverse (solve). +# It creates a special "matrix", which is really a list containing a function to: +# set the value of the matrix +# get the value of the matrix +# set the value of the solve +# get the value of the solve makeCacheMatrix <- function(x = matrix()) { - + s <- NULL + set <- function(y) { + x <<- y + s <<- NULL + } + get <- function() x + setsolve <- function(solve) s <<- solve + getsolve <- function() s + list(set = set, get = get, + setsolve = setsolve, + getsolve = getsolve) } -## Write a short comment describing this function - +## cacheSolve: This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. +# If the inverse has already been calculated (and the matrix has not changed), +# then cacheSolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + # Return a matrix that is the inverse of 'x' + s <- x$getsolve() + if(!is.null(s)) { + message("getting cached solve") + return(s) + } + data <- x$get() + # Computing the inverse of a square matrix can be done with solve(x) + s <- solve(data, ...) + x$setsolve(s) + s }