2017-08-07 179 views
0

我想在coursEra上運行這個R編程課程的例子。然而,當我試圖確定矩陣是否爲方形,我得到錯誤說:「在is.square.matrix錯誤(X):參數x不是矩陣」R:函數來確定矩陣是否是正方形

我的代碼如下:

library(matrixcalc) 
##non-square matrix 
NCols <- sample(3:6, 1) 
NRows <- sample(2:8, 1) 

myMat <- matrix(runif(NCols*NRows), ncol=NCols) 
is.square.matrix(myMat) 

## functions 
makeMatrix <- function(x = matrix()) { 
    m <- NULL 
    set <- function(y) { 
    x <<- y 
    m <<- NULL 
    } 
    get <- function() x 
    setInv <- if (is.square.matrix(x) == TRUE) { 
    function(solve) m <<- solve 
    } 
    { 
    function(ginv) m <<- ginv 
    } 
    getInv <- function() m 
    list(x, set = set, get = get, 
     setInv = setInv, 
     getInv = getInv) 
} 

cacheMatrix <- function(x, ...) { 
    m <- x$getInv() 
    if(!is.null(m)) { 
    message("getting cached data") 
    return(m) 
    } 
    data <- x$get() 
    m <- if (is.square.matrix(x) == TRUE) { 
    solve(data, ...) 
    } 
    { 
    ginv(data, ...) 
    } 
    x$setInv(m) 
    m 
} 

## run functions for matrix 
notSquare <- makeMatrix(myMat) 
cacheMatrix(notSquare) 


##check 
ginv(myMat) 

然後我得到的錯誤:

Error in is.square.matrix(x) : argument x is not a matrix

我是初學者所以不知道如何讓sentInv識別和檢查矩陣是方形或沒有。

布賴恩

回答

0

沒關係。在使用(x = matrix())替換x所需的makeMatrix函數中,並在cacheMatrix中將x替換爲(data)

+0

請發表正確的代碼。其他SO用戶可能會感興趣。 –

0

下面是答案。我只是做了函數(x)而不是函數(x = matrix()),並且'data'是在緩存函數中拉取矩陣的變量,需要我有這個輸入。

##non-square matrix 
NCols <- sample(3:6, 1) 
NRows <- sample(2:8, 1) 

myMat <- matrix(runif(NCols*NRows), ncol=NCols) 
is.square.matrix(myMat) 

## functions 
makeCacheMatrix <- function(x) { 
     m <- NULL 
     set <- function(y) { 
       x <<- y 
       m <<- NULL 
     } 
     get <- function() x 
     setInv <- if (is.square.matrix(x) == TRUE) { 
       function(solve) m <<- solve 
     } 
     else { 
       function(ginv) m <<- ginv 
     } 
     getInv <- function() m 
     list(x, set = set, get = get, 
      setInv = setInv, 
      getInv = getInv) 
} 

cacheSolve <- function(x, ...) { 
     m <- x$getInv() 
     if(!is.null(m)) { 
       message("getting cached data") 
       return(m) 
     } 
     data <- x$get() 
     m <- if (is.square.matrix(data) == TRUE) { 
       solve(data, ...) 
     } 
     else { 
       ginv(data, ...) 
     } 
     x$setInv(m) 
     m 
} 

## run functions for myMat 
notSquare <- makeCacheMatrix(myMat) 
cacheSolve(notSquare) 


##check 
ginv(myMat) 
相關問題