稀疏矩阵的快速装配

时间:2016-10-17 16:43:09

标签: matlab sparse-matrix

我有索引

I = [nGrid x 9] matrix % mesh on fine grid (9 point rectangle)
J = [nGrid x 4] matrix % mesh on coarse grid (4 point rectangle)

此处,nGrid是大数,具体取决于网格(例如1.e05)

然后我想做

R_ref = [4 x 9] matrix % reference restriction matrix from fine to coarse
P_ref = [9 x 4] matrix % reference prolongation matrix from coarse to fine

R = sparse(size) % n_Coarse x n_Fine
P = sparse(size) % n_Fine x n_Coarse
for k = 1 : nGrid % number of elements on coarse grid
    R(I(k,:),J(k,:)) = R_ref;
    P(J(k,:),I(k,:)) = P_ref;
end

size是预定的数字。

请注意,即使(I,J)中有相同的索引,我也不想累积。我只想分别在每个索引处放置模板RrefPref

我知道由于稀疏的数据结构,这很慢。

通常,我使用

sparse(row,col,entry,n_row,n_col)

我可以通过IJ操纵R_refP_refbsxfunrepmat来使用此功能。

但是,由于sparse功能

的累积,无法做到这一点

(如果(i,j)存在[row(i),col(i)]==[row(j),col(j)],那么R(row(i),row(j)) = entry(i)+entry(j)

对于这种装配程序有什么建议吗?

示例代码

%% INPUTS
% N and M could be much larger
N = 2^5+1; % number of fine grid in x direction
M = 2^5+1; % number of fine grid in y direction


% [nOx * nOy] == nGrid
nOx = floor((M)/2)+1; % number of coarse grid on x direction
nOy = floor((N)/2)+1; % number of coarse grid on y direction

Rref = [4     4    -1     4    -2     0    -1     0     0
    -1    -1    -2     4     4     4    -1     4     4
    -1    -1     4    -2     4    -2     4     4    -1
    0     4     4     0     0     4    -1    -2    -1]/8;

Pref = [2     1     0     1     0     0     0     0     0
    0     0     0     1     1     1     0     1     2
    0     0     1     0     1     0     2     1     0
    0     2     1     0     0     1     0     0     0]'/2;


%% INDEX GENERATION
tri_ref = reshape(bsxfun(@plus,[0,1,2]',[0,N,2*N]),[],1)';
TRI_ref = reshape(bsxfun(@plus,[0,1]',[0,nOy]),[],1)';
I = reshape(bsxfun(@plus,(1:2:N-2)',0:2*N:(M-2)*N),[],1);
J = reshape(bsxfun(@plus,(1:nOy-1)',0:nOy:(nOx-2)*nOy),[],1);
I = bsxfun(@plus,I,tri_ref);
J = bsxfun(@plus,J,TRI_ref);


%% THIS PART IS WHAT I WANT TO CHANGE
R = sparse(nOx*nOy,N*M);
P = R';
    for k = 1 : size(I,1)
    R(J(k,:),I(k,:)) = Rref;
    P(I(k,:),J(k,:)) = Pref;
end

0 个答案:

没有答案