From 2e577e326f3c81d320f1b78f278a072850c0a051 Mon Sep 17 00:00:00 2001 From: Manoj Xavier Date: Wed, 20 Aug 2014 00:38:29 +0800 Subject: [PATCH 1/2] Added completed cachematrix.R --- cachematrix.R | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..330c5e84202 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -4,6 +4,17 @@ ## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { + inv <- NULL + set <- function(y) { + x <<- y + inv <<- NULL + } + get <- function() x + setinverse <- function(solve) inv <<- solve + getinverse <- function() inv + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } @@ -12,4 +23,17 @@ makeCacheMatrix <- function(x = matrix()) { cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' + inv <- x$getinverse() + if(!is.null(inv)) { + message("getting cached data") + return(inv) + } + data <- x$get() + inv <- solve(data, ...) + x$setinverse(inv) + inv } + +a = matrix( c(4,10,23,12), nrow=2, ncol=2) +mat <- makeCacheMatrix(a) +cacheSolve(mat) From 6b44e4ac0c0df0b315e4222a6bd9f94a6fb306a4 Mon Sep 17 00:00:00 2001 From: Manoj Xavier Date: Wed, 20 Aug 2014 01:05:31 +0800 Subject: [PATCH 2/2] Added comments --- cachematrix.R | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index 330c5e84202..b8f2d3d49ea 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,7 +1,11 @@ -## Put comments here that give an overall description of what your -## functions do +## makeCacheMatrix creates special "matrix" whereas the cacheSolve returns the inverse of the +## matrix from cache, if it exists there. if not, it computes the inverse and returns it. -## Write a short comment describing this function +## makeCacheMatrix creates a special "matrix" ,which is a list containing a function to +## 1. set the value of the matrix +## 2. get the value of the matrix +## 3. set the inverse of the matrix +## 4. get the inverse of the matrix makeCacheMatrix <- function(x = matrix()) { inv <- NULL @@ -19,7 +23,8 @@ makeCacheMatrix <- function(x = matrix()) { } -## Write a short comment describing this function +## cacheSolve returns the inverse of a matrix if it exists in the cache. +## if not, it computes the inverse and returns it cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' @@ -34,6 +39,8 @@ cacheSolve <- function(x, ...) { inv } +## Test both functions with test data a = matrix( c(4,10,23,12), nrow=2, ncol=2) mat <- makeCacheMatrix(a) cacheSolve(mat) +cacheSolve(mat)