Fastest way to set up a sparse matrix in matlab

I am working with iterative methods and hence large sparse matrices. For example, I want to create 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, only some of the diagonals are nonzero. In my programming I will work with much larger matrix sizes, but the idea is the same: only a few diagonals are nonzero, all other entries are zeros.

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

+3


source to share


1 answer


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

      

+5


source







All Articles