caching - Returning the inverse matrix from a cached object in R checking that input matrix has not changed -
disclosure: programming assignment coursera course called r programming. had full code took parts of out since realize not permitted upload full code (granted code uploaded didn't work).
the assignment regarding lexical scoping , caching functions may require long computation time. using solve() find inverse of matrix , cache using free floating variable. trying cache input matrix can retrieve , compare new input matrices. returning error on latter described below.
first, run both makecachematrix , cachesolve per code below.
the first function, makecachematrix creates special "matrix" object can cache input matrix , inverse
makecachematrix <- function(x = matrix()) { m <- null # sets value of m null (provides default if cachesolve has not yet been used) y <- null # sets value of y null (provides default if cachesolve has not yet been used) setmatrix <- function(y) { #set value of matrix x <<- y ## caches inputted matrix cachesolve can check whether has changed (note within setmatrix function) m <<- null # # sets value of m (the matrix inverse if used cachesolve) null } # parts removed list(setmatrix = setmatrix, getmatrix = getmatrix, # creates list house 4 functions setinverse = setinverse, getinverse = getinverse) } the second function cachesolve calls functions stored in special "matrix" returned makecachematrix (above). if inverse has been calculated (and matrix has not changed), cachesolve retrieves inverse cache. if input new, calculates inverse of data , sets inverse in cache via setinverse function.
cachesolve <- function (x=matrix(), ...) { # need compare matrix there before! m <- x$getinverse() # if inverse has been calculated gets if(!is.null(m)){ # check see if cachesolve has been run before if(x$setmatrix() == x$getmatrix()) { # check matrix hasn't changed, , if hasn't, sends text message , returns cached matrix #parts removed return(m) } # otherwise y <- x$getmatrix() # run getmatrix function value of input matrix x$setmatrix(y) # run setmatrix function on input matrix cache m <- solve(y, ...) # compute value of inverse of input matrix x$setinverse(m) # run setinverse function on inverse cache inverse m # return inverse }
then test using following code:
mat <- matrix(data = c(4,2,7,6), nrow = 2, ncol = 2) mat2 <- makecachematrix(mat) cachesolve(mat2) this gives inverse expected.
but when try test cache capability running same matrix again.
cachesolve(mat2) it returns "error in x$setmatrix() : argument "y" missing, no default. however, thought provided default null in second line of makecachematrix. expected give message "getting cached data" , inverse.
what doing wrong? how can cache input matrix using setmatrix , provide default y?
try cachesolve <- function (x, ...) , perform if(!is.null(m)) test. luck.
Comments
Post a Comment