diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..619b681d2a8 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,48 @@ -## Put comments here that give an overall description of what your -## functions do +## Coursera - R Programming - Programming Assignment 2 (peer assessment) +## +## Author - https://github.com/JoeData/ProgrammingAssignment2/ +## +## Functions - makeCacheMatrix, cacheSolve -## Write a short comment describing this function -makeCacheMatrix <- function(x = matrix()) { +## makeCacheMatrix accepts matrix, gets its inverse and stores inverse in cache +makeCacheMatrix <- function(x = matrix()) { + + ## setting variables + m <- NULL + set <- function(y) { + x <<- y + m <<- NULL + } + + ## inverting matrix and storing in cache + get <- function() x + setInverse <- function(solve) m <<- solve + getInverse <- function() m + list(set = set, get = get, + setInverse = setInverse, + getInverse = getInverse) } -## Write a short comment describing this function +## cacheSolve accepts matrix, checks if its inverse is cached +## if cached, returns the cached inverted matrix +## if not cached, inverts the matrix and returns cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + + m <- x$getInverse() + + ## checking if inverted matrix is cached and if so, returns + if(!is.null(m)) { + message("getting cached data") + return(m) + } + + ## if not in cache, inverts and returns + data <- x$get() + m <- solve(data, ...) + x$setInverse(m) + m }