From 998c5832dab7fcac93c36ebb2b50ce2b22db3dd6 Mon Sep 17 00:00:00 2001 From: Yvan Wibaux Date: Thu, 14 Jan 2016 16:32:09 +0100 Subject: [PATCH] assignement inverse matrix cached --- cachematrix.R | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..30ca25efb7a 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,37 @@ -## Put comments here that give an overall description of what your -## functions do +## Matrix inversion is usually a costly computation and there may be some benefit +## to caching the inverse of a matrix rather than compute it repeatedly -## Write a short comment describing this function +## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { - + inverse <- NULL + set <- function(y) { + x <<- y + inverse <<- NULL + } + get <- function() x + setInverse <- function(i) inverse <<- i + getInverse <- function() inverse + list(set = set, get = get, + setInverse = setInverse, + getInverse = getInverse) } -## Write a short comment describing this function +## This function computes the inverse of the special "matrix" +## returned by makeCacheMatrix above. +## If the inverse has already been calculated (and the matrix has not changed), +## then the cachesolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + inverse <- x$getInverse() + if(!is.null(inverse)) { + message("getting cached data") + return(inverse) + } + data <- x$get() + inverse <- solve(x$get(), ...) + x$setInverse(inverse) + inverse }