DON'T WRITE YOUR OWN CODE FOR A PROBLEM LIKE THIS.
Instead, just create the tridiagonal matrix, as a sparse matrix. Then use backslash to do the solve. All of that is literally trivial, requiring not much more than two calls, one to spdiags, and a second to backslash. Instead, you spent probably hours writing messy, heavily looped, unreadable, uncommented, and un-debuggable code that you got wrong. and now cannot fix.
Use MATLAB as it is designed to be used.
Create an nx3 array of the elements on the three diagonals. Call spdiags. Use backslash, or perhaps linsolve or decomposition as you wish.

