Use R to implement an algorithm to compute the LU factorization of banded matrices (you can ignore pivoting). The inputs to your function should be a matrix A and its bandwidth w (your algorithm does not need to determine the bandwidth, you can assume it will be provided by the user). The outputs should be a list of two matrices L and U .
lu_with_bandwidth <- function(A, bandwidth) {
n <- nrow(A)
L <- diag(n)
U <- matrix(0, nrow = n, ncol = n)
for (i in 1:n) {
start_col <- max(1, i - bandwidth)
end_col <- min(n, i + bandwidth)
U[i, i:end_col] <- A[i, i:end_col]
if (start_col <= end_col) {
L[start_col:end_col, i] <- A[start_col:end_col, i] / U[i, i]
if (i < n) {
A[(i+1):end_col, (i+1):end_col] <- A[(i+1):end_col, (i+1):end_col] - L[(i+1):end_col, i] %*% U[i, (i+1):end_col]
}
}
}
return(list(L = L, U = U))
}
B <- matrix (c(3,1,4,0,0,0,1,5,9,2,0,0,6,5,3,5,8,0,0,9,7,9,3,2,0,0,3,8,4,6,0,0,0,2,6,4), nrow=6)
print(lu_with_bandwidth(B,2))
Output error: Error in A[(i + 1):end_col, (i + 1):end_col] - L[(i + 1):end_col, i] %*% : non-conformable arrays
here is the algorithm i follow. algorithm
If you add the drop=FALSE parameter to the indexing of L and U you will get further. R's
[function will drop dimensions for single column or row matrices.But I don't know if that is correct or not. (It does have a banded structure so it might be.)