From 933a6d3899411bb1f95da6ac091afdbe41545a50 Mon Sep 17 00:00:00 2001 From: Beres Botond Date: Sun, 27 Jul 2014 15:32:10 +0200 Subject: [PATCH 1/2] First version of the functions --- cachematrix.R | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..40426ab0869 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,39 @@ ## 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 which is really +# a list containing a function to +# 1. set the value of the matrix +# 2. get the value of the matrix +# 3. set the value of the inverse +# 4. get the value of the 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 - +# The following function calculates the inverse of the special "matrix" +# created with makeCacheMatrix. +# However, it first checks for an already cached inverse and skips +# the computation if it finds one. 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) + } + data <- x$get() + inv <- solve(data, ...) + x$setinverse(inv) + inv } From ac187f1d838647091834ac760566387fb19380a7 Mon Sep 17 00:00:00 2001 From: Beres Botond Date: Sun, 27 Jul 2014 15:38:24 +0200 Subject: [PATCH 2/2] Fixed a bug and finished comments --- cachematrix.R | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index 40426ab0869..94dca87c287 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,5 +1,4 @@ -## Put comments here that give an overall description of what your -## functions do +# The functions below provide a way to cache matrix inversions # This function creates a special matrix which is really # a list containing a function to @@ -27,7 +26,7 @@ makeCacheMatrix <- function(x = matrix()) { # the computation if it finds one. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' - inv <= x$getinverse() + inv <- x$getinverse() if(!is.null(inv)) { message("getting cached data!") return(inv)