jeudi 26 septembre 2019

How do I use if-statements in regards to inverses of matrices?

Everything works how I want it to apart from the final if statement. I want "Singular product" to be returned if the product of X and Y does not have an inverse.

The following is the code I have thus far, and it doesn't work for the final matrices.

question.five <- function(X,Y) {
if(is.matrix(X)==F) stop("X not matrix")
else { if(is.matrix(Y)==F) stop("Y not matrix")
else { if(ncol(X)!=nrow(Y)) stop("X and Y are not conformable")
else { if(solve(X%*%Y)==ERROR) stop("Singular product")
else on.exit(print(solve(X%*%Y)))
}}}}
X <- matrix(c(1,2,3,4),2,2)
Y <- c(1,2,3,4)
question.five(X,Y)
X <- matrix(c(1,3,4,5),2,2)
Y <- matrix(c(3,2,4,2,4,5,1,2,3),3,3)
question.five(X,Y)
X <- matrix(c(1,-1,-3,4),2,2)
Y <- matrix(c(4,1,3,1),2,2)
question.five(X,Y)

So again, this part of the code is what I need help with:

if(solve(X%*%Y)==ERROR) stop("Singular product")

Aucun commentaire:

Enregistrer un commentaire