A <- matrix(c(2,-5,4,1,-2.5,1,1,-4,6),byrow=T,nrow=3,ncol=3)
b <- matrix(c(-3,5,10),nrow=3,ncol=1)
p <- nrow(A)
U.pls <- cbind(A,b)
for (i in 1:p){
for (j in (i+1):(p+1)) U.pls[i,j] <- U.pls[i,j]/U.pls[i,i]
U.pls[i,i] <- 1
if (i < p) {
for (k in (i+1):p) U.pls[k,] <-
U.pls[k,] - U.pls[k,i]/U.pls[i,i]*U.pls[i,]
}
}
U.pls
x <- rep(0,p)
for (i in p:1){
if (i < p){
temp <- 0
for (j in (i+1):p) temp <- temp + U.pls[i,j]*x[j]
x[i] <- U.pls[i,p+1] - temp
}
else x[i] <- U.pls[i,p+1]
}
x
output
> U.pls
[,1] [,2] [,3] [,4]
[1,] 1 -2.5 2 -1.5
[2,] 0 1.0 -Inf Inf
[3,] 0 0.0 1 NaN
> x
[1] NaN NaN NaN
In this way, I cannot solve solution in some case. Even though I know the reason why the error happens mathematically, I cannot fix the error in R. Help me with some fix. Thank you in advance.
You can do gauss elimination through
pracma
library.To install it you can type:
Then, use it as follows:
The result is:
Gauss <- function () { A <- matrix ( c ( 2 , -5 , 4 , 1 , 4 , 1 , 1 , -4 , 6 ), byrow = T , nrow = 3 , ncol = 3 ) b <- matrix ( c ( -3 , 5 , 10 ), nrow = 3 , ncol = 1 ) U.pls <- cbind (A,b) p <- nrow ( A )
}
Sorry if this answer is too late.
I've wrote a function to make the gaussian elimination
Note:
i) This function only works with real numbers and not with variables.
ii) In the return at the end I have used the function as.fractions().This is only available in the MASS package and you need to have at least R version 3.2.5 or newer to use it. You can ommit this is if you want but the elements of the matrixes will be as decimals.
iii) This function also returns the matrixes used in the decomposition PA = LDU If you want only the decomposition PA = LU use as a second argument FALSE.
Hope this help!
I had to reorder you matrix
A
, don't know how do a generic code:EDIT: