From 2f88133bdf2f59ba0c66af01ec5157c019a1ebaf Mon Sep 17 00:00:00 2001 From: Ivan Selchenkov Date: Sat, 26 Apr 2014 18:36:41 +0400 Subject: [PATCH 1/2] Caching the Inverse of a Matrix --- cachematrix.R | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..2c63e717533 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,37 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## This is a couple of functions which is used to cache +## inverse of a matrix +## Creates a special object to store inverse of a matrix makeCacheMatrix <- function(x = matrix()) { - + inv <- NULL + + ## get & set original matrix (unused in this task) + set <- function(m) { + x <<- m + inv <<- NULL + } + get <- function() x + + ## get & set the inverse of a matrix + setinv <- function(inverse) inv <<- inverse + getinv <- function() inv + + list(set = set, get = get, setinv = setinv, getinv = getinv) } -## Write a short comment describing this function - +## Returns the inverse of matrix 'x'. +## If the inverse is not present in cache, will calculate it and store to cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inv <- x$getinv() + + if(!is.null(inv)) { + message("getting cached data") + return (inv) + } + data <- x$get() + inv = solve(data, ...) + x$setinv(inv) + + inv } From 4ed39d46a3b0e5ddfc4d64a8a1729b99b8d70794 Mon Sep 17 00:00:00 2001 From: Ivan Selchenkov Date: Sun, 27 Apr 2014 20:28:58 +0400 Subject: [PATCH 2/2] comment changed --- cachematrix.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cachematrix.R b/cachematrix.R index 2c63e717533..a29fbfc0059 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -5,7 +5,7 @@ makeCacheMatrix <- function(x = matrix()) { inv <- NULL - ## get & set original matrix (unused in this task) + ## get & set original matrix set <- function(m) { x <<- m inv <<- NULL