# creating a function that works the same as forward solve()

``````my_forward_sub <- function(L, b, ...) {

# for scalars not conformable
if(length(L) == 1 & length(b) != 1) {

return("Error: not conformable")

}
# for conformable scalars
if(length(L) == 1) {

return( b[1] / L)

}

# check conformability of matrices
if(ncol(L) != length(b)) {

return("Error: not conformable")

}

#check its a lower triangular matrix (NB will only consider lower and upper)
if( !is.lower.tri(L)) {

return("Error: L is not a lower triangular matrix")

} else {

x <- vector()

x[1] <- b[1]/L[1,1]

for(i in 2:nrow(L)){
b[i]=b[i]
for(j in dim(L)[1]: i-1 ){
b[i]=b[i]-L[i,j]*x[j]
}
x[i]=(b[i]-x[i+1]*x[i])/L[i,i]
}
return(x)
}
}
``````

the function must accept a lower triangular matrix(of any size) 'L' and a solution vector 'b' as arguments and must return the solution vector x by using forward substitution. the code above is what I have managed to put together so far but it only gives the first solution and then 'NA' for the rest. please assist in what I need to change so that it gives the full answer.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.