简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM