From 45d300e09edb5e00206bd53693005483cf44410f Mon Sep 17 00:00:00 2001 From: Hojoon Ji Date: Sun, 13 Apr 2014 23:23:22 +0900 Subject: [PATCH 1/2] first save --- cachematrix.R | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..17e6e585c7c 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,34 @@ -## Put comments here that give an overall description of what your -## functions do +############################################################################### +# Calculate inverse matrix and cache the result for reusablity +############################################################################### -## Write a short comment describing this function +## Initialize orgMat variable to x as soon as this object is created. makeCacheMatrix <- function(x = matrix()) { - + orgMat <- NULL + inverseMat <- NULL + setMat <- function(mat) { + orgMat <<- mat + inverseMat <<- NULL + } + getMat <- function() orgMat + setInverseMat <- function(mat) inverseMat <<- mat + getInverseMat <- function() inverseMat + setMat(x) + list(setMat = setMat, getMat = getMat, setInverseMat = setInverseMat, + getInverseMat = getInverseMat) } - -## Write a short comment describing this function - +# return cache data if exists +# otherwise use solve function to calculate inverse matrix and save to +# caller object cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inverseMat <- x$getInverseMat() + if (!is.null(inverseMat)) { + message("getting from cache") + return (inverseMat) + } + x$setInverseMat(solve(x$getMat())) + inverseMat <- x$getInverseMat() + inverseMat } From b35e81a04b4208e7816657ec99b4bcc59ee3b10a Mon Sep 17 00:00:00 2001 From: Hojoon Ji Date: Sun, 13 Apr 2014 23:35:54 +0900 Subject: [PATCH 2/2] Add new comments --- cachematrix.R | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/cachematrix.R b/cachematrix.R index 17e6e585c7c..2fe84d4a862 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -3,18 +3,26 @@ ############################################################################### -## Initialize orgMat variable to x as soon as this object is created. +# Initialize orgMat variable to x as soon as this object is created. makeCacheMatrix <- function(x = matrix()) { orgMat <- NULL inverseMat <- NULL + + # save original matrix setMat <- function(mat) { orgMat <<- mat inverseMat <<- NULL } + # return original matrix getMat <- function() orgMat + # save inverse matrix setInverseMat <- function(mat) inverseMat <<- mat + # return inverse matrix getInverseMat <- function() inverseMat + + # initialize orgMat var setMat(x) + list(setMat = setMat, getMat = getMat, setInverseMat = setInverseMat, getInverseMat = getInverseMat) }