Search code examples
matlabmatrixsparse-matrix

Create sparse band matrix in matlab with variable distance of elements


I want to create a sparse matrix in matlab for calculating the second derivative. Currently I create it in the following way:

r_num = 1000;
r_square_num = r_num*r_num;
A = sparse(-30*diag(ones(r_square_num,1),0)+16*diag(ones(r_square_num-r_num,1),r_num)+16*diag(ones(r_square_num-r_num,1),-r_num)-diag(ones(r_square_num-2*r_num,1),-2*r_num)-diag(ones(r_square_num-2*r_num,1),2*r_num));

But that way is impossible due to diag and ones creating dense matrices, which will overflow my memory. If the position of the secondary and ternary diagonals is already known in beforehand, then I can rewrite it in the following way:

A = spdiags([-1*ones_vec 16*ones_vec -30*ones_vec 16*ones_vec -1*ones_vec], -2:2, r_square_num, r_square_num);

But how can I do that if the distance between the diagonals is depending on r_num?


Solution

  • The 2nd input argument (d) can be any vector, e.g. [-1:1], [-2,0,2] or [-5,3]. Thus, the following should work:

    A = spdiags([-1*ones_vec 16*ones_vec -30*ones_vec 16*ones_vec -1*ones_vec], (-2:2)*r_num, r_square_num, r_square_num);