Search code examples
arraysmatlabmatrixsparse-matrixsparse-array

The fastest way to set up sparse matrix in matlab


I am working with iterative methods, and thus with large sparse matrices. For instance, I want to set up a matrix like this:

1   1   0   0   1   0   0   0   0   0
1   1   1   0   0   1   0   0   0   0
0   1   1   1   0   0   1   0   0   0
0   0   1   1   1   0   0   1   0   0
1   0   0   1   1   1   0   0   1   0
0   1   0   0   1   1   1   0   0   1

So that only certain diagonals are non-zero. In my programming, I will be working with much larger matrix sizes, but Idea is the same: Only a few diagonals are non-zero, all other entries are zeros.

I know, how to do it in for loop, but it seems to be not effective, if the matrix size is large. Also I work with symmetric matrices. I would appreciate, if you provide me a code for my sample matrix along with description.


Solution

  • You want spdiags:

    m = 6;                       %// number of rows
    n = 10;                      %// number of columns
    diags = [-4 -1 0 1 4];       %// diagonals to be filled
    A = spdiags(ones(min(m,n), numel(diags)), diags, m, n);
    

    This gives:

    >> full(A)
    ans =
         1     1     0     0     1     0     0     0     0     0
         1     1     1     0     0     1     0     0     0     0
         0     1     1     1     0     0     1     0     0     0
         0     0     1     1     1     0     0     1     0     0
         1     0     0     1     1     1     0     0     1     0
         0     1     0     0     1     1     1     0     0     1