0

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?

Mugge
  • 1
  • 1
  • 1
    In the inner loop, the part `b[i-i]` looks awfully suspicious. – DanY Sep 13 '22 at 16:16
  • It does, it was a typo. But the code still doesn't run well... – Mugge Sep 13 '22 at 16:17
  • You have `L[3,1]` in the 3x3 case, not of the form `L[i,i-1]`. – Stéphane Laurent Sep 13 '22 at 16:40
  • Recommend not using the same object name for input and output in your functions. Rather create a new output object in your function and return that. E.g. x <- vector() at the top then return(x). – SteveM Sep 13 '22 at 16:50
  • Thanks for the replies! I still can't get it run properly... Our notes says we should try to compute this expression: $$x_{i}=\frac{b_{i}-\sum_{j=1}^{i-1} a_{ij}x_{j}}{a_{ii}}$$ – Mugge Sep 13 '22 at 17:04

0 Answers0