From 483a2cb0c4939e46e4903ac052b6f8cd176932e1 Mon Sep 17 00:00:00 2001 From: Lawrence Lin Date: Sun, 27 Apr 2014 14:55:39 +0800 Subject: [PATCH 1/2] Complete the functions. --- cachematrix.R | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..414f6e64ccb 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,35 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function - +## funtcion makeCacheMatrix() 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 + setInverse <- function(solve) m <<- solve + getInverse <- function() m + list(set = set, get = get, + setInverse = setInverse, + getInverse = getInverse) } +## cacheSolve() 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, ...) { + m <- x$getInverse() -## Write a short comment describing this function + ## Return a matrix that is the inverse of 'x' if the inverse has already been calculated and cached. + if(!is.null(m)) { + message("getting cached data") + return(m) + } -cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Calculate the inverse of 'x' if the cached data doesn't exist. + data <- x$get() + m <- solve(data, ...) + x$setInverse(m) + + ## Return a matrix that is the inverse of 'x' + m } From b185518c6d9a5feb8fd5259c4cabd611731f1860 Mon Sep 17 00:00:00 2001 From: Lawrence Lin Date: Sun, 27 Apr 2014 15:01:45 +0800 Subject: [PATCH 2/2] Typo fixed, more comments added. --- cachematrix.R | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index 414f6e64ccb..8d4a5c643a6 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,4 +1,10 @@ -## funtcion makeCacheMatrix() creates a special "matrix" object that can cache its inverse. +## function makeCacheMatrix() creates a special "matrix" object that can cache its inverse. +## There are several functions: +## 1. set the value of the matrix +## 2. get the value of the matrix +## 3. set the inverse of the matrix +## 4. get the inverse of the matrix + makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y) { @@ -19,7 +25,7 @@ makeCacheMatrix <- function(x = matrix()) { cacheSolve <- function(x, ...) { m <- x$getInverse() - ## Return a matrix that is the inverse of 'x' if the inverse has already been calculated and cached. + ## Return a matrix that is the inverse of 'x' if the inverse has already been calculated and cached. if(!is.null(m)) { message("getting cached data") return(m)