From e89020d1f3a8ac62f6aa3269d8b5990c1daafb16 Mon Sep 17 00:00:00 2001 From: Vasyl Dizhak Date: Fri, 19 Feb 2016 16:17:31 +0100 Subject: [PATCH] Programmin assignment 2, implement cacheSolve function to calculate inverted matrix --- cachematrix.R | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..a7b5901083a 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,36 @@ -## Put comments here that give an overall description of what your -## functions do +## Introduce `makeCacheMatrix` constructor function and `cacheSolve` function in +## order to optimize getting of inverted matrix by caching already calculated results. -## Write a short comment describing this function +## Constuctor function for matrix object +## with stores inverted version of it. makeCacheMatrix <- function(x = matrix()) { - + inverted <- NULL; + set <- function(y) { + x <<- y + inverted <<- NULL + } + get <- function() x + setinverted <- function(invertedValud) inverted <<- invertedValud + getinverted <- function() inverted + list(set = set, get = get, + setinverted = setinverted, + getinverted = getinverted) } -## Write a short comment describing this function +## Returns inverted matrix either from the cached version +## or by explicitely calculating it with help of `solve` function. +## x has to be `makeCacheMatrix` object. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inverted <- x$getinverted() + if(!is.null(inverted)) { + message("getting cached data") + return(inverted) + } + data <- x$get() + inverted <- solve(data, ...) + x$setinverted(inverted) + inverted }