From 5db54a7a0aad828af68f9b98a4cff9ec53d48498 Mon Sep 17 00:00:00 2001 From: Michael Nowell Date: Mon, 6 Nov 2023 19:11:50 +0800 Subject: [PATCH 1/2] First Save --- cachematrix.R | 1 + 1 file changed, 1 insertion(+) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..088ef03aa1d 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,3 +1,4 @@ +##Second GIT Project ## Put comments here that give an overall description of what your ## functions do From b2f7a23315da1b69f0a057d6256e56637d48080f Mon Sep 17 00:00:00 2001 From: Michael Nowell Date: Mon, 6 Nov 2023 19:28:16 +0800 Subject: [PATCH 2/2] Matrix and invertible function --- cachematrix.R | 67 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 57 insertions(+), 10 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index 088ef03aa1d..ba79a7e2712 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,16 +1,63 @@ -##Second GIT Project -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function - makeCacheMatrix <- function(x = matrix()) { - + ## @x: a square invertible matrix + ## return: a list containing functions to + ## 1. set the matrix + ## 2. get the matrix + ## 3. set the inverse + ## 4. get the inverse + ## this list is used as the input to cacheSolve() + + inv = NULL + set = function(y) { + # use `<<-` to assign a value to an object in an environment + # different from the current environment. + x <<- y + inv <<- NULL + } + get = function() x + setinv = function(inverse) inv <<- inverse + getinv = function() inv + list(set=set, get=get, setinv=setinv, getinv=getinv) } +cacheSolve <- function(x, ...) { + ## @x: output of makeCacheMatrix() + ## return: inverse of the original matrix input to makeCacheMatrix() + + inv = x$getinv() + + # if the inverse has already been calculated + if (!is.null(inv)){ + # get it from the cache and skips the computation. + message("getting cached data") + return(inv) + } + + # otherwise, calculates the inverse + mat.data = x$get() + inv = solve(mat.data, ...) + + # sets the value of the inverse in the cache via the setinv function. + x$setinv(inv) + + return(inv) +} -## Write a short comment describing this function +##Test function -cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' +test = function(mat){ + ## @mat: an invertible matrix + + temp = makeCacheMatrix(mat) + + start.time = Sys.time() + cacheSolve(temp) + dur = Sys.time() - start.time + print(dur) + + start.time = Sys.time() + cacheSolve(temp) + dur = Sys.time() - start.time + print(dur) } + \ No newline at end of file