From 63b57c4806286f29950868acd02c85076a7c5332 Mon Sep 17 00:00:00 2001 From: WilsonTW Date: Fri, 25 Sep 2015 17:37:33 +0800 Subject: [PATCH] my w3 programming assignment --- cachematrix.R | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..8ae7c82e081 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 +## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { - + inv <- NULL + set <- function(y) { + x <<- y + inv <<- NULL + } + get <- function() x + setinverse <- function(inverse) inv <<- inverse + getinverse <- function() inv + list(set = set, + get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function +## 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' + inv <- x$getinverse() + if (!is.null(inv)) { + message("getting cached data") + return(inv) + } + mat <- x$get() + inv <- solve(mat, ...) + x$setinverse(inv) + inv }