From 7b8c1ec99090dbd99a07d23e44a780079a51c946 Mon Sep 17 00:00:00 2001 From: Jerome Jia Date: Mon, 22 Dec 2014 02:29:37 +0800 Subject: [PATCH] submission for peer assessment --- .gitignore | 3 +++ cachematrix.R | 37 +++++++++++++++++++++++++++++++------ 2 files changed, 34 insertions(+), 6 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000000..807ea251739 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.Rproj.user +.Rhistory +.RData diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..cb8d9b2a6e7 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,40 @@ -## Put comments here that give an overall description of what your -## functions do +## A set of functions that aids frequent access of results of matrix inversion operations, +## best fit for matrices with large dimensions. -## Write a short comment describing this function +## Function to create a special matrix whose inversion is cached for subsequent access makeCacheMatrix <- function(x = matrix()) { - + i <- NULL + set <- function(y) { + x <<- y + i <<- NULL + } + get <- function() x + setinv <- function(inv) i <<- inv + getinv <- function() i + list(set = set, get = get, + setinv = setinv, + getinv = getinv) } -## Write a short comment describing this function +## Function to retrieve the inversion of any matrix created via makeCacheMatrix if already +## cached, otherwise calculcates the inversion and cache it for the matrix cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## returns NA if x is not properly created via makeCacheMatrix + if(!"getinv" %in% names(x) | !"setinv" %in% names(x)) { + warning("input matrix not wrapped by makeCacheMatrix") + return(NA) + } + ## Return a matrix that is the inverse of 'x' + i <- x$getinv() + if(!is.null(i)) { + message("getting cached data") + return(i) + } + data <- x$get() + i <- solve(data, ...) %*% data + x$setinv(i) + i }