MATLAB Answers

## Sparse indexing expression is likely to be slow

Ignatius Tommy Pratama

### Ignatius Tommy Pratama (view profile)

さんによって質問されました 2017 年 10 月 26 日

### Cedric Wannaz (view profile)

さんによって 編集されました 2017 年 10 月 26 日
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 件のコメント

サインイン to comment.

## 2 件の回答

### Walter Roberson (view profile)

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 件のコメント

サインイン to comment.

2017 年 10 月 26 日

### Cedric Wannaz (view profile)

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 件のコメント

サインイン to comment.

Translated by