diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..2a3511d0426 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,46 @@ -## Put comments here that give an overall description of what your -## functions do +## +## R Programming, Assignment 2 +## Uses lexical scoping to create and cache the inverted matrix of a given matrix. +## -## Write a short comment describing this function +# these lines are just for testing... +#rm(list=ls()) +#setwd("~/Personal/Coursera/RProgramming/Labs/ProgrammingAssignment2"); +#getwd() -makeCacheMatrix <- function(x = matrix()) { +## makeCacheMatrix(x) +## x is a matrix +## returns a list of functions to manipulate x: +## set(), get(), setinverse(), and getinverse() +makeCacheMatrix <- function(x = matrix()) { + invm <- NULL + set <- function(y) { + x <<- y + invm <<- NULL + } + get <- function() x + setinverse <- function(m) invm <<- m + getinverse <- function() invm + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function - +## Return a matrix that is the inverse of 'x' (created by makeCacheMatrix) +## and caches it in the object x cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + invm <- x$getinverse() + + if(!is.null(invm)) { + message("getting cached data") + return(invm) + } + + data <- x$get() + invm <- solve(data, ...) + x$setinverse(invm) + invm } + diff --git a/cachevector.R b/cachevector.R new file mode 100644 index 00000000000..d0bfd62fb6e --- /dev/null +++ b/cachevector.R @@ -0,0 +1,25 @@ + makeVector <- function(x = numeric()) { + m <- NULL + set <- function(y) { + x <<- y + m <<- NULL + } + get <- function() x + setmean <- function(mean) m <<- mean + getmean <- function() m + list(set = set, get = get, + setmean = setmean, + getmean = getmean) + } + + cachemean <- function(x, ...) { + m <- x$getmean() + if(!is.null(m)) { + message("getting cached data") + return(m) + } + data <- x$get() + m <- mean(data, ...) + x$setmean(m) + m + }