I'm an R newbie and I'm trying to set up this simple Gaussian elimination code, but I keep receiving 2 errors and I'm not sure how to fix them.
Error 1: Error in a[i, j] <- a[i, j] - multiplier * a[k, j] :
replacement has length zero
Error 2: Error in a[i, j] : subscript out of bounds
Here's the code I have:
#Set Up Matrix
a <- matrix(c(0,2,3,2,1,1,5,1,0), byrow=T,nrow=3,ncol=3)
colnames(a) <- c("x","y","z")
k <- c(1,2,3)
b <- matrix(c(1,1,2),nrow = 3,ncol=1)
rownames(b) <- c("i","j","k")
colnames(b) <- "b"
#Print a and b
a
b
#Row Counter
n <- nrow(a)
###### Forward Elimination ######
#Loop over all rows in matrix except last
for (k in 1:n-1)
{
#Loop over all rows below the diagonal position k,k
for (i in k+1:n)
{
#Compute Multiplier for row i and column k
multiplier = a[i,k]/a[k,k]
#Loop over all columns to the right of the diagonal position k,k
for (j in k + 1:n)
{
#Update coefficient for row i and column j
a[i,j] = a[i,j] - multiplier * a[k,j]
}
#Update right hand side for row i and column j
b[i] = b[i] - multiplier*b[j]
}
}
###### Back Substitution ######
#Loop backwards over all rows except last
for (i in n:-1)
{
sum = 0
#Loop over all columns to the right of the current row
for (j in i+1:n)
{
sum = sum + a[i,j]*x[j]
#Compute (i)th unknown
x(i) = (b[i]- sum)/a[i,i]
}
}