From 6c3d8532da6c4d3f0e873b2001922dd361d21233 Mon Sep 17 00:00:00 2001 From: Ludovic Claude Date: Sun, 24 May 2015 23:19:40 +0200 Subject: [PATCH] Wrote the cache matrix functions --- cachematrix.R | 45 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..c8547d94b0f 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,48 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## 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. +## makeCacheMatrix and cacheSolve can be used to create a matrix that is able to cache its inverse. +## Typical usage: +## ```` +## m <- makeCacheMatrix(matrix(1:4,2,2)) +## cacheSolve(m) +## m$get() +## cacheSolve(m) +## ```` +## makeCacheMatrix creates a special "matrix", which is really a list containing a function to +## 1. set the value of the matrix +## 2. get the value of the matrix +## 3. set the value of the inverse matrix +## 4. get the value of the inverse metrix makeCacheMatrix <- function(x = matrix()) { + + i <- NULL + set <- function(y) { + x <<- y + i <<- NULL + } + get <- function() x + setinverse <- function(inverse) i <<- inverse + getinverse <- function() i + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function +## cacheSolve takes a cached matrix as argument and returns the inverse of the matrix. +## The inverse is stored inside the cached matrix on first call, then retrived from the cache on subsequent calls. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + i <- x$getinverse() + if(!is.null(i)) { + message("getting cached data") + return(i) + } + data <- x$get() + i <- solve(data, ...) + x$setinverse(i) + i }