From b4f5c09d49f520f5148b51f1c7d9956dcbb023e2 Mon Sep 17 00:00:00 2001 From: newxcombr Date: Sat, 17 Jan 2015 21:13:41 -0200 Subject: [PATCH 1/2] add code for makeCacheMatrix and cacheSolve functions --- cachematrix.R | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..9d6b9b95b77 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,30 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function - 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 - cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + inverse <- x$getinverse() + if(!is.null(inverse)) { + message("getting cached inverse matrix") + return(inverse) + } + + data <- x$get() + message("computing inverse matrix") + inverse <- solve(data, ...) + x$setinverse(inverse) + inverse } + From 9575946af1c08db6764da2ea51ade9c92c00610d Mon Sep 17 00:00:00 2001 From: newxcombr Date: Sat, 17 Jan 2015 21:40:15 -0200 Subject: [PATCH 2/2] add comments to methods --- cachematrix.R | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/cachematrix.R b/cachematrix.R index 9d6b9b95b77..015246b815a 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,3 +1,11 @@ +#Creates a special "matrix" object that can cache its inverse +# Args: +# x: a square invertible matrix object +# +# Returns: +# A special "matrix" based on a list object that provides +# a get/set methods to the original matrix object and a +# get/set methods to the inversed (and cached) matrix makeCacheMatrix <- function(x = matrix()) { inverse <- NULL set <- function(y) { @@ -12,7 +20,14 @@ makeCacheMatrix <- function(x = matrix()) { getinverse = getinverse) } - +# Checks whether or not whe have a cached inversed matrix. +# Returns the cached object if found, otherwise computes the inverse matrix using R "solve" method +# +# Args: +# x: a square invertible matrix object +# +# Returns: +# An inverse matrix of x matrix (cached or computed) cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' inverse <- x$getinverse()