%% Extract Nonzero Diagonals from Matrix
% Extract the nonzero diagonals of a matrix and examine the output format of spdiags.
%
% Create a matrix containing a mix of nonzero and zero diagonals.

A = [0     5     0    10     0     0
     0     0     6     0    11     0
     3     0     0     7     0    12
     1     4     0     0     8     0
     0     2     5     0     0     9];

%
% Extract the nonzero diagonals from the matrix. Specify two outputs to return the diagonal numbers.

[Bout,d] = spdiags(A)

% The columns of the first output Bout contain the nonzero diagonals of A. The second output d lists the indices of the nonzero diagonals of A. The longest nonzero diagonal in A is in column 3 of Bout. To give all columns of Bout the same length, the other nonzero diagonals of A have extra zeros added to their corresponding columns in Bout. For m-by-n matrices with m < n, the rules are:
% For nonzero diagonals below the main diagonal of A, extra zeros are added at the tops of columns (as in the first two columns of Bout).
% For nonzero diagonals above the main diagonal of A, extra zeros are added at the bottoms of columns (as in the last column of Bout).
% spdiags pads Bout with zeros in this manner even if the longest diagonal is not returned in Bout.
% Copyright 2019 The MathWorks, Inc.