| MATLAB Function Reference | ![]() |
Extract and create sparse band and diagonal matrices
Syntax
[B,d] = spdiags(A) B = spdiags(A,d) A = spdiags(B,d,A) A = spdiags(B,d,m,n)
Description
The spdiags function generalizes the function diag. Four different operations, distinguished by the number of input arguments, are possible:
[B,d] = spdiags(A)
extracts all nonzero diagonals from the m-by-n matrix A. B is a min(m,n)-by-p matrix whose columns are the p nonzero diagonals of A. d is a vector of length p whose integer components specify the diagonals in A.
B = spdiags(A,d)
extracts the diagonals specified by d.
A = spdiags(B,d,A)
replaces the diagonals specified by d with the columns of B. The output is sparse.
A = spdiags(B,d,m,n)
creates an m-by-n sparse matrix by taking the columns of B and placing them along the diagonals specified by d.
Arguments
The spdiags function deals with three matrices, in various combinations, as both input and output:
Roughly, A, B, and d are related by
for k = 1:p
B(:,k) = diag(A,d(k))
end
Some elements of B, corresponding to positions outside of A, are not defined by these loops. They are not referenced when B is input and are set to zero when B is output.
Examples
Example 1. This example generates a sparse tridiagonal representation of the classic second difference operator on n points.
e = ones(n,1); A = spdiags([e -2*e e], -1:1, n, n)
Turn it into Wilkinson's test matrix (see gallery):
A = spdiags(abs(-(n-1)/2:(n-1)/2)',0,A)
Finally, recover the three diagonals:
B = spdiags(A)
Example 2. The second example is not square.
A = [11 0 13 0
0 22 0 24
0 0 33 0
41 0 0 44
0 52 0 0
0 0 63 0
0 0 0 74]
The statement [B,d] = spdiags(A) produces d = [-3 0 2]' and
B = [41 11 0
52 22 0
63 33 13
74 44 24]
Conversely, with the above B and d, the expression spdiags(B,d,7,4) reproduces the original A.
Example 3. This example shows how spdiags creates the diagonals when the columns of B are longer than the diagonals they are replacing.
B = repmat((1:6)',[1 7])
B =
1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5 5
6 6 6 6 6 6 6
d = [-4 -2 -1 0 3 4 5];
A = spdiags(B,d,6,6);
full(A)
ans =
1 0 0 4 5 6
1 2 0 0 5 6
1 2 3 0 0 6
0 2 3 4 0 0
1 0 3 4 5 0
0 2 0 4 5 6
See Also
| spconvert | speye | ![]() |