2017-05-30 67 views
1

我想在matlab中創建一個稀疏矩陣來計算二階導數。目前,我在下面的方式來創建它:在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)); 

但這種方式是不可能的,因爲diagones創造密集矩陣,這會溢出我的記憶中。如果二次和三元對角線的位置在事先已經知道,那麼我可以通過以下方式重寫一遍:

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對角線之間的距離?

回答

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);