Selecting some vectors from a matrix

I am trying to write a code for band matrices that store only the nonzero vectors. For example if I have tridiagonal matrix of size 10, I want to store only the three diagonals as a vectors. n here represent the band size

bandmat[mat_, n_] := Module[{k = Dimensions[mat], mt = mat, v},

For[i = 1, i <= n, i++,

For[j = 1, j <= k - (i - 1), j++,

v[[j]] = Array[mt, {j, j + i - 1}]];];

Return[v]]

but it doesn't work. can you tell me please what I did wrong?

• Use a SparseArray – b3m2a1 Jan 27 at 2:59
• Table[Diagonal[mat,i],{i,-1,1}] will return those three diagonals of mat. – Bill Jan 27 at 3:07
• Bill but this is an example, but in genera how to know the domain of i? – strange world Jan 27 at 4:03
• Ah, I did not realize that this was likely a homework question and I try to not do homework for people because learning how to solve a problem on your own is far more important than learning how to ask someone to do the problem for you. A hint: Perhaps you could extract all the diagonals and then choose the ones that satisfy your condition or eliminate those which do not satisfy your condition. – Bill Jan 27 at 5:38