我想在matlab中创建一个稀疏矩阵来计算二阶导数。目前我按以下方式创建它:
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));
但是这种方式是不可能的,因为diag
和ones
会创建密集的矩阵,这会溢出我的记忆。如果事先已知二级和三级对角线的位置,那么我可以通过以下方式重写它:
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);
但如果对角线之间的距离取决于r_num
,我怎么能这样做?
答案 0 :(得分:2)
第二个输入参数(d
)可以是任何向量,例如[-1:1]
,[-2,0,2]
或[-5,3]
。因此,以下内容应该有效:
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);