Good night. I have a homework of Coursera. But i have two days stuck trying to solve my problem.
My homework is:
Write the following functions:
makeCacheMatrix: This function creates a special "matrix" object that can cache its inverse. cacheSolve: This function 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. Computing the inverse of a square matrix can be done with the solve function in R. For example, if X is a square invertible matrix, then solve(X) returns its inverse.
I use the library matlib for calculate the inverse of the matrix.
library(matlib)
makeCacheMatrix <- function(x = matrix()) {
if (ncol(x)==nrow(x) && det(x)!=0) {
m<-NULL
set<-function(y){
x<<-y
m<<-NULL
}
get<-function() x
setinverse <- function() m <<- inv(x)
getinverse<-function() m
list(set=set,get=get,setinverse=setinverse,getinverse=getinverse)
}else{
return(message("The matrix is'n invertible."))
}
}
cacheSolve <- function(x, ...) {
m<-x$getinverse
if (!is.null(m)) {
message("getting cached data")
return(m)
}
data<-x$get
m <- inv(data, ...)
x$setinverse(m)
m
}
But when i'm trying for example test my code
x<-makeCacheMatrix(matrix(c(1,0,0,0,1,0,0,0,2),ncol=3,nrow=3))
x$get()
x$getinverse()
I obtain a NULL result. I don't know what's problem with my code. Can someone help me?