From 2514d8491898cef7c1a2ccc5ef80f800db234191 Mon Sep 17 00:00:00 2001 From: hoangh Date: Tue, 22 Apr 2014 19:46:37 +1000 Subject: [PATCH] Update cachematrix.R --- cachematrix.R | 62 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 57 insertions(+), 5 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..3c2095d366b 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,67 @@ -## Put comments here that give an overall description of what your -## functions do +# =============================================================================================== +# =============================================================================================== +# =============================================================================================== -## Write a short comment describing this function +# makeCacheMatrix function creates a special "matrix" object that can cache its inverse +# It contains a list of functions as follow: +# set the value of the input matrix +# get the value of the input matrix +# set the value of the inverse matrix +# get the value of the inverse matrix makeCacheMatrix <- function(x = matrix()) { + # initialize inverse matrix + inv <- NULL + # set matrix value + set <- function(y) { + x <<- y + inv <<- NULL + } + + # get matrix value + get <- function() x + # set inverse matrix + setinv <- function(inv_) inv <<- inv_ + # get inverse matrix + getinv <- function() inv + + # list of all functions + list(set = set, get = get, + setinv = setinv, + getinv = getinv) } -## Write a short comment describing this function +# =============================================================================================== +# =============================================================================================== +# =============================================================================================== + +# This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. +# If the inverse has already been calculated (and the matrix has not changed), then the cachesolve +# should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + # if the inverse is already exist then cache + inv <- x$getinv() + if(!is.null(inv)) { + message("getting cached data") + return(inv) + } + + data <- x$get() + + # Calculate inverse matrix using solve function + inv <- solve(data, ...) + + # cache that inverse matrix + x$setinv(inv) + + # return + inv } + +# =============================================================================================== +# =============================================================================================== +# =============================================================================================== +