From 44dd7aa7db73df79ba760beb5343cae5b18304f7 Mon Sep 17 00:00:00 2001 From: Miguel Rocha Date: Mon, 21 Apr 2014 18:29:25 +0100 Subject: [PATCH 1/2] solved the assignment --- cachematrix.R | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..810872a0c73 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,41 @@ ## Put comments here that give an overall description of what your ## functions do -## Write a short comment describing this function +## This function creates a list with functions to create the cached matrix and its inverse +## each field contains a function: set (sets the matrix), get (returns the matrix), +## setinv (sets the inverse), getinv (returns the inverse) makeCacheMatrix <- function(x = matrix()) { - + inv = NULL + set = function(mat) + { + m <<- mat + inv <<- NULL + } + get = function() m + setinv = function(mi) inv <<- mi + getinv = function() inv + + res = list(set = set, get = get, setinv = setinv, getinv = getinv) + res$set(x) + res } -## Write a short comment describing this function +## Computes the inverse: gest from cache if it is computed or computes it, if it is not +## Returns the inverse cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' + + inv = x$getinv() + if (!is.null(inv)) + { + message ("getting cached data") + return(inv) + } + mat = x$get() + inv = solve(mat) + x$setinv(inv) + inv } From 100fda0f7e1aeebfb16758ba2c93c55521d5cefc Mon Sep 17 00:00:00 2001 From: Miguel Rocha Date: Mon, 21 Apr 2014 18:33:13 +0100 Subject: [PATCH 2/2] solved the assignment --- cachematrix.R | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/cachematrix.R b/cachematrix.R index 810872a0c73..78d7c10ede5 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -7,17 +7,24 @@ makeCacheMatrix <- function(x = matrix()) { inv = NULL + ## set function set = function(mat) { m <<- mat inv <<- NULL } + # get function get = function() m + # setinv function setinv = function(mi) inv <<- mi + # getinv function getinv = function() inv + # builds the list res = list(set = set, get = get, setinv = setinv, getinv = getinv) + # needed to store the matrix when creating cache res$set(x) + # returns the list res } @@ -29,13 +36,22 @@ cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' inv = x$getinv() + ## if inverse is calculated return cached inverse if (!is.null(inv)) { message ("getting cached data") return(inv) } + ## else compute it and return it mat = x$get() inv = solve(mat) x$setinv(inv) inv } + +## example code to run +## m1 = matrix(rnorm(16), 4, 4) +## cm1 = makeCacheMatrix(m1) +## cacheSolve(cm1) +## cacheSolve(cm1) +## second run gets the result from cache