From 576adc5986b26908ebaa1d37da7890933bb2f732 Mon Sep 17 00:00:00 2001 From: Darlesson Date: Thu, 15 Aug 2019 11:59:32 -0700 Subject: [PATCH] Programming Assignment 2: Lexical Scoping --- cachematrix.R | 47 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..a8e0dd5d5b0 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,50 @@ -## Put comments here that give an overall description of what your -## functions do +## Cache matrix inversion -## Write a short comment describing this function +## Create a matrix object to cache it's inverse +## Example of usage cacheSolve(makeCacheMatrix(matrix(c(1, 3, 2, 4), 2,2))) makeCacheMatrix <- function(x = matrix()) { - + + m <- NULL + + set <- function (y) { + x <<- y + m <<- NULL + } + + get <- function () { + x + } + + setInverse <- function (inverseMatrix) { + + if (hasArg(inverseMatrix)) + # Set inversed matrix + m <<- inverseMatrix + else + # Invert current matrix + m <<- solve(x) + } + + getInverse <- function () { + m + } + + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } -## Write a short comment describing this function +## Returns a matrix inverted from x +## x should come from makeCacheMatrix cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + + m <- x$getInverse() + + if (is.null(m)) { + m <- solve(x$get()) + x$setInverse(m) + } + + m }