From 084d5513d9fa9b40ac1e78f896276e266c174681 Mon Sep 17 00:00:00 2001 From: Sieverts Date: Sat, 26 Apr 2014 18:36:52 +0100 Subject: [PATCH] submitted version of cachematrix.R --- cachematrix.R | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..5920b287b78 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,38 @@ -## Put comments here that give an overall description of what your -## functions do +## This file consists of two functions. The first, makeCacheMatrix, creates a +## special "matrix" object that can cache its inverse. The second, cacheSolve, computes the inverse +## of the output of makeCacheMatrix, unless the inverse has already been calculated in which +## case it is retrieved from the cache. -## Write a short comment describing this function +## makeCacheMatrix is a function that creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { - + m <- NULL + set <- function(y) { + x <<- y + m <<- NULL + } + get <- function() x + setinv <- function(solve) m <<- mean + getinv <- function() m + list(set = set, get = get, + setinv = setinv, + getinv = getinv) + } -## Write a short comment describing this function +## cacheSolve computes the inverse of the special "matrix" returned by makeCacheMatrix. +## If the inverse has already been calculated then it is retrieved from the cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + m <- x$getinv() + if(!is.null(m)) { + message("getting cached data") + return(m) + } + data <- x$get() + m <- solve(data, ...) + x$setinv(m) + m }