Sparse indexing expression is likely to be slow
조회 수: 2 (최근 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!