Sparse indexing expression is likely to be slow
6 次查看(过去 30 天)
显示 更早的评论
Currently, I am working on 2D FDM equation. With that code arrangement, the running time is negligible for a relatively small matrix (e.g., 2000 x 2000). But with a bigger matrix (e.g., 20000 x 20000), that code runs very slowly.
N = Nx*Ny; %Number of unknowns
M = sparse(N,N); %Creating zeros matrix
BC = sparse(N,1); %Creating zeros boundary condition matrix
%%Define the 2D FDM equation to the interior points
for i = 2:Nx-1 %Loop over x-direction, skipping 1st and last grid points
for j = 2:Ny-1 %Loop over y-direction, skipping 1st and last grid points
n = i+(j-1)*Nx; %Convert ij grid point to the n-th grid point
M(n,n) = -4; %Main diagonal
M(n,n-1) = 1; %Off diagonal to the left
M(n,n+1) = 1; %Off diagonal to the right
M(n,n-Nx) = 1; %Far off diagonal to the left
M(n,n+Nx) = 1; %Far off diagonal to the right
BC(n,1) = 0;
end
end
Is there any suggestion to improve the previous code? Any help would be really great!
0 个评论
回答(2 个)
Walter Roberson
2017-10-26
If you are going to assign into a sparse array, then you should create it using spalloc() indicating the number of non-zero elements expected.
Each time you assign exceeding the non-zero count associated with the array, the array has to be copied into new memory.
0 个评论
Cedric
2017-10-26
编辑:Cedric
2017-10-26
When building sparse matrices using an iterative approach, it is often more efficient to build vectors of indices and values iteratively, and to build the sparse matrix at the end as a one shot operation:
n = ...
I = .. prealloc
J = .. prealloc
V = .. prealloc
for ...
Defined elements of I, J, V
end
M = sparse( I, J, V, n, n ) ;
Note that in your case it may be possible to define I, J, V without using an iterative approach, and/or to use SPDIAGS.
0 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!