From d9c2e140acd3231f6c1663fe05e547ef9f29b200 Mon Sep 17 00:00:00 2001 From: caldwellsa Date: Wed, 23 Apr 2014 22:07:32 -0700 Subject: [PATCH] commit completed assignment --- cachematrix.R | 51 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..b17ab700c3d 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,56 @@ -## Put comments here that give an overall description of what your -## functions do +## makeCacheMatrix is a function that creates an object that stores a +## matrix and corresponding inverted matrix and four functions to manage +## them. -## Write a short comment describing this function +## set(y) stores the matrix, and sets the inverse to NULL (since the +## old value is invalid and needs to be recalculated) +## get() retrieves the matrix +## setmatrix(xinv) stores the inverted matrix +## getmatrix() retrieves the inverted matrix makeCacheMatrix <- function(x = matrix()) { - + m <- NULL + set <- function(y) { + x <<- y + m <<-NULL + } + get <- function() x + setmatrix <- function(xinv) m <<- xinv + getmatrix <- function() m + list (set=set, get=get, setmatrix=setmatrix, getmatrix=getmatrix) } +## cacheSolve checks if there is a cached value and returns the value if +## available, otherwise recaculates the inverse and caches the new value -## Write a short comment describing this function cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' + m <- x$getmatrix() + if (!is.null(m)) { + message("getting cached matrix...") + return(m) + } + xm <- x$get() ## xm gets the non-inverted matrix + m <- solve(xm, ...) ## m is the inverted matrix solution to be cached + x$setmatrix(m) } + +## usage example: +# > obj <- makeCacheMatrix() +# > obj$set(matrix(1:4,nrow=2,ncol=2)) +# > obj$get() +# [,1] [,2] +# [1,] 1 3 +# [2,] 2 4 +# > cacheSolve(obj) +# > obj$getmatrix() +# [,1] [,2] +# [1,] -2 1.5 +# [2,] 1 -0.5 +# > cacheSolve(obj) +# getting cached matrix... +# [,1] [,2] +# [1,] -2 1.5 +# [2,] 1 -0.5 +# >