From 16ec9c26067cc1693fcf31113dc2b3f13ecae9f2 Mon Sep 17 00:00:00 2001 From: "P.Fwu" Date: Sun, 20 Apr 2014 10:47:00 -0400 Subject: [PATCH] work done --- .Rhistory | 19 +++++++++++++++++++ cachematrix.R | 49 ++++++++++++++++++++++++++++++++++++++++++++----- cmd.R | 7 +++++++ 3 files changed, 70 insertions(+), 5 deletions(-) create mode 100644 .Rhistory create mode 100644 cmd.R diff --git a/.Rhistory b/.Rhistory new file mode 100644 index 00000000000..ef6a4d983e1 --- /dev/null +++ b/.Rhistory @@ -0,0 +1,19 @@ +?solve +m<-matrix(1:16, 4, 4) +View(m) +intm<-solve(m) +rnorm(16) +m<-matrix(rnorm(16)), 4, 4) +m<-matrix(rnorm(16), 4, 4) +intm<-solve(m) +source('cachematrix.R') +t1<- cacheSolve(m) +source('cachematrix.R') +t1 <- makeCacheMatrix(m) +t1 +cacheSolve(t1) +cacheSolve(makeCacheMatrix(m)) +solve(m) +t1$get() +t1$getInv() +getwd() diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..0bfee337216 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,54 @@ -## Put comments here that give an overall description of what your -## functions do +# implement cache to solve inverse matrix +# +# ex: +# my_matrix <- matrix(rnorm(16)), 4, 4) +# my_inverse_matrix <- cacheSolve(makeCacheMatrix(my_matrix)) -## Write a short comment describing this function + +## Creat cache matrix with a list of four functions makeCacheMatrix <- function(x = matrix()) { + m <- NULL + + # set the matrix value + set <- function(y){ + x <<- y + m <<- NULL + } + + # get matrix value + get <- function() x + + # set inverse matrix value + setInv <- function(im) m <<- im + + # get inverse matrix value + getInv <- function() m + list(set = set, get = get, + setInv = setInv, + getInv = getInv) } -## Write a short comment describing this function +## solve the inverse matirx from cache matrix cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + # obtain inverse matrix, if not yet computed, NULL will be returned + m <- x$getInv() + + # if inverse matrix has been computed already, return the exisiting + # result and end the function + if(!is.null(m)){ + message("getting cached data") + return(m) + } + + # get matrix value + data <- x$get() + + # compute inverse matrix and return + m <- solve(data, ...) + x$setInv(m) + m } diff --git a/cmd.R b/cmd.R new file mode 100644 index 00000000000..564fe1348d9 --- /dev/null +++ b/cmd.R @@ -0,0 +1,7 @@ +m <- NULL +set <- function(x) m <<-x + +set(2) + +## +source('cachematrix.R')