From 6c5072bc8830623dba55656fe1f89f1a1f6a76b0 Mon Sep 17 00:00:00 2001 From: searli Date: Fri, 25 Jul 2014 10:55:42 +0100 Subject: [PATCH] Updated cachematrix.R for Programming Assignment 2 --- cachematrix.R | 39 ++++++++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..a0affdb6bed 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,44 @@ -## Put comments here that give an overall description of what your -## functions do +## makeCacheMatrix: +## This function creates a special "matrix" object +## that can cache its inverse. +## +## cacheSolve: +## 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 cacheSolve should retrieve the inverse from the cache. -## Write a short comment describing this function -makeCacheMatrix <- function(x = matrix()) { +## 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(solve) inverse <<- solve + getinverse <- function() inverse + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function +## Computes the inverse of the special "matrix" returned by makeCacheMatrix cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' + m <- x$getinverse() + if(!is.null(m)) { + message("getting cached data") + return(m) + } + data <- x$get() + m <- solve(data, ...) + x$setinverse(m) + m } + +