From ec4c7c8cf0b6a912b7c8797ba911d47b8b3b86bd Mon Sep 17 00:00:00 2001 From: Paulo Schneider Date: Wed, 15 Jul 2015 18:04:59 +0100 Subject: [PATCH] Cache inverse of a matrix --- cachematrix.R | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..cf1d1589c64 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,34 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## This file provides a set of functions for caching the inverse of a matrix, for performance reasons. +## Creates an object that represents a cached matrix. It exposes the following functions: +## - set: set the value of the matrix +## - get: get the value of the matrix +## - setinverse: set the inverse of the matrix +## - getinverse: get the inverse of the matrix makeCacheMatrix <- function(x = matrix()) { - + inverse <- NULL + set <- function(y) { + x <<- y + inverse <<- NULL + } + get <- function() x + setinverse <- function(inv) inverse <<- inv + getinverse <- function() inverse + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function - +## Returns the inverse of a matrix, preferabily through its cached value. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inverse <- x$getinverse() + if(!is.null(inverse)) { + message("getting cached data") + return(inverse) + } + data <- x$get() + inverse <- solve(data, ...) + x$setinverse(inverse) + inverse }