From 48e1d340013b2b3b3aeaccbdaf439457e4f7b960 Mon Sep 17 00:00:00 2001 From: jirisanHunter Date: Fri, 25 Apr 2014 14:29:23 +0900 Subject: [PATCH] cachematrix.R --- cachematrix.R | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..bc9a0312e81 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,10 +1,22 @@ -## Put comments here that give an overall description of what your -## functions do +## These functions calculate and cache the inverses of matrices and then return +## the cached inverses when the same matrix is sent. -## Write a short comment describing this function -makeCacheMatrix <- function(x = matrix()) { +## makeCacheMatrix() function sets and returns matrices and calculates their +## inverses, deposits them in a cache and then returns the inverse matix when +## the inverse of the same matrices were requested +makeCacheMatrix <- function(x = matrix()) { + invMtrx <- NULL + set <- function(y) { + x <<- y + invMtrx <<- NULL + } + get <- function() {x} + setInv <- function(inv) {invMtrx <<- inv} + getInv <- function() {invMtrx} + + list(set = set, get = get, setInv = setInv, getInv = getInv) } @@ -12,4 +24,14 @@ makeCacheMatrix <- function(x = matrix()) { cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' + invMtrx <- x$getInv() + if(!is.null(invMtrx)) { + message("getting cached data") + return(invMtrx) + } + + data <- x$get() + invMtrx <- solve(data, ...) + x$setInv(invMtrx) + invMtrx }