# Sparse indexing expression is likely to be slow

12 views (last 30 days)
Ignatius Tommy Pratama on 26 Oct 2017
Edited: Cedric Wannaz on 26 Oct 2017
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!

Walter Roberson on 26 Oct 2017
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.

Cedric Wannaz on 26 Oct 2017
Edited: Cedric Wannaz on 26 Oct 2017
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.