spdiags
Extracts diagonals from a matrix, or builds a matrix from diagonals.
Category: Mathematics > Sparse Matrices
Syntax
B = spdiags(A)
Returns the nonzero diagonals of A as the columns of B.
[B, d] = spdiags(A)
Also returns the diagonal numbers d.
S = spdiags(B, d, m, n)
Builds an m-by-n sparse matrix whose diagonals d are taken from the columns of B.
S = spdiags(B, d, A)
Replaces the diagonals d of A with the columns of B.
Description
A band matrix such as the second-difference operator is written compactly by listing its diagonals. A column of B shorter than the diagonal is padded: for a square matrix, a superdiagonal uses the entries of B from the bottom, and a subdiagonal uses them from the top, so the first entries of an upper diagonal and the last entries of a lower diagonal are ignored.
Extraction is the inverse: spdiags(A) finds which diagonals are not empty and returns them in the same layout, ready to be fed back to the building form.
Input arguments
A- Matrix to extract from, or to modify.
B- Matrix whose columns hold the diagonal values.
d- Vector of diagonal numbers:
0is the main diagonal, positive values are above it, negative below. m, n- Size of the matrix to create.
Output arguments
B- Matrix with one diagonal per column, padded with zeros.
S- Sparse matrix with the requested diagonals.
Example
Second-difference matrix
e = ones(4, 1);
A = spdiags([-e 2*e -e], -1:1, 4, 4);
full(A)
[B, d] = spdiags(A);
d
ans = 4×4
2 -1 0 0
-1 2 -1 0
0 -1 2 -1
0 0 -1 2
d = 3×1
-1
0
1