I have to write a program which takes a lower triangular matrix L
and a vector b
as input, and a solution x
as output.
So first I computed a trivial program which only can handle 3x3 triangular matrices.
L3solve <- function(L,b) {
b[1] <- b[1] / L[1,1]
b[2] <- (b[2] - L[2,1]*b[1]) / L[2,2]
b[3] <- (b[3] - L[3,1]*b[1] - L[3,2]*b[2]) / L[3,3]
return(b)
}
After that I made a generalized version of it:
Lsolve <- function(L,b) {
b[1] <- b[1] / L[1,1]
for(i in 2:nrow(L)) {
b[i] <- (b[i] - sum(L[i,i-1]*b[i-1])) / L[i,i]
}
return(b)
}
But this version doesn't work. Can anybody tell me what I'm doing wrong?