From 79adc39667e2079107b7fac309de50a76ffd657b Mon Sep 17 00:00:00 2001 From: miktro Date: Fri, 9 Jan 2015 15:32:21 +0000 Subject: [PATCH 1/2] Completed and tested the 2 functions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Completed and tested the 2 functions. Used system.time to compare speed of solve vs cacheSolve on a 10x10 matrix. cacheSolve was (only) 12 times faster¬! --- cachematrix.R | 50 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa4..2f13838e6e 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 - -makeCacheMatrix <- function(x = matrix()) { - -} - - -## Write a short comment describing this function - -cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' -} +## Put comments here that give an overall description of what your +## functions do + +## This creates a new object that stores a matrix +## together with it's inverse - initially set to NULL + +makeCacheMatrix <- function(x = matrix()) { + mi <- NULL + set <- function(y) { + x <<- y + mi <<- NULL + } + get <- function() x + setinverse <- function(inv) mi <<- inv + getinverse <- function() mi + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) +} + + +## Write a short comment describing this function + +cacheSolve <- function(x, ...) { + ## Return a matrix that is the inverse of 'x' + mi <- x$getinverse() + if(!is.null(mi)) { + #message("getting cached matrix inverse") + return(mi) + } + data <- x$get() + mi <- solve(data, ...) + x$setinverse(mi) + mi +} From 0582334e02bf9a6ad3bc8253b7688931cd0d465d Mon Sep 17 00:00:00 2001 From: miktro Date: Fri, 9 Jan 2015 15:35:35 +0000 Subject: [PATCH 2/2] Added comment to cacheSolve --- cachematrix.R | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cachematrix.R b/cachematrix.R index 2f13838e6e..e91407d7fe 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -19,7 +19,9 @@ makeCacheMatrix <- function(x = matrix()) { } -## Write a short comment describing this function +## cacheSolve checks supplied object to see if it has an inverse already. +## If there is an inverse then it is returned. +## Otherwise the inverse is 'solve'd, stored for furture use and returned. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x'