From 9ece66c39a415a8c9a004c715fcd141f69a6943a Mon Sep 17 00:00:00 2001 From: Phews Date: Wed, 16 Apr 2014 22:34:10 +0300 Subject: [PATCH 1/2] Assignment completed --- cachematrix.R | 60 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 52 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..01f0c62bcd6 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,59 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## These functions are meant for implementing cached version of +## solve function. The solution is based on a special kind of matrix +## that can cache the results of the solve function. +## +## Example usage: +## matrx = makeCacheMatrix() +## B = matrix( c(1, 2, 3, 4),nrow=2, ncol=2) +## matrx$setMatrix(B) +## result = cacheSolve(matrx) +## print(result) +## makeCacheMatrix function creates a matrix that can store results of +## matrix inverse in cache. +## Functions available in created matrix: setMatrix, getMatrix, setInverse, getInverse makeCacheMatrix <- function(x = matrix()) { - + + i <- NULL + + setMatrix <- function(y) { + m <<- y + i <<- NULL + } + getMatrix <- function() m + setInverse <- function(inverse) i <<- inverse + getInverse <- function() i + list(setMatrix = setMatrix, getMatrix = getMatrix, + setInverse = setInverse, + getInverse = getInverse) } -## Write a short comment describing this function - +## cacheSolve function calculates matrix inverse. If result has already +## been calculated and cached then function results cached result instead cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + + i <- x$getInverse() + + ## Check if cached result exists + if(!is.null(i)) { + return(m) + } + data <- x$getMatrix() + + ## calculate inverse matrix + i <- solve(data, ...) + x$setInverse(i) + i } + +## Function for testing the functionality of the cached matrix +testCachedMatrix <- function() { + matrx = makeCacheMatrix() + B = matrix( c(1, 2, 3, 4),nrow=2, ncol=2) + matrx$setMatrix(B) + result = cacheSolve(matrx) + print(result) +} + +testCachedMatrix() From 3b274a3296b800e38a2ec7075fe9e51eb668e607 Mon Sep 17 00:00:00 2001 From: Phews Date: Wed, 16 Apr 2014 22:35:07 +0300 Subject: [PATCH 2/2] Small bug fix --- cachematrix.R | 2 -- 1 file changed, 2 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index 01f0c62bcd6..7bff9c644ad 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -55,5 +55,3 @@ testCachedMatrix <- function() { result = cacheSolve(matrx) print(result) } - -testCachedMatrix()