1function C = diag (A, k)
2%DIAG diagonal matrices and diagonals of a matrix.
3% C = diag (v,k) when v is a vector with n components is a square sparse
4% matrix of dimension n+abs(k), with the elements of v on the kth
5% diagonal. The main diagonal is k = 0; k > 0 is above the diagonal, and
6% k < 0 is below the main diagonal.  C = diag (v) is the same as
7% C = diag (v,0).
8%
9% c = diag (A,k) when A is a matrix returns a column vector c formed the
10% entries on the kth diagonal of A.  The main diagonal is c = diag (A).
11%
12% The GraphBLAS diag function always constructs a GraphBLAS sparse matrix,
13% unlike the built-in MATLAB diag, which always constructs a MATLAB full
14% matrix.  To use this overloaded function for a MATLAB sparse matrix A,
15% use C = diag (A, GrB (k)) ;
16%
17% Examples:
18%
19%   C1 = diag (GrB (1:10, 'uint8'), 2)
20%   C2 = sparse (diag (1:10, 2))
21%   nothing = double (C1-C2)
22%
23%   A = magic (8)
24%   full (double ([diag(A,1) diag(GrB(A),1)]))
25%
26%   m = 5 ;
27%   f = ones (2*m,1) ;
28%   A = diag(-m:m) + diag(f,1) + diag(f,-1)
29%   G = diag(GrB(-m:m)) + diag(GrB(f),1) + diag(GrB(f),-1)
30%   nothing = double (A-G)
31%
32% See also GrB/diag, spdiags, GrB/tril, GrB/triu, GrB.select.
33
34% SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
35% SPDX-License-Identifier: GPL-3.0-or-later
36
37if (isobject (A))
38    A = A.opaque ;
39end
40
41if (nargin < 2)
42    k = 0 ;
43else
44    k = gb_get_scalar (k) ;
45end
46
47[am, an, atype] = gbsize (A) ;
48a_is_vector = (am == 1) || (an == 1) ;
49
50if (a_is_vector)
51
52    % ensure A is a column vector
53    if (am == 1)
54        A = gbtrans (A) ;
55    end
56
57    % ensure A is not hypersparse
58    [~, s] = gbformat (A) ;
59    if (isequal (s, 'hypersparse'))
60        A = gbnew (A, 'sparse') ;
61    end
62
63    % C = diag (v,k) where v is a column vector and C is a matrix
64    C = GrB (gbmdiag (A, k)) ;
65
66else
67
68    % v = diag (A,k) is a column vector formed from the elements of the kth
69    % diagonal of A
70    C = GrB (gbvdiag (A, k)) ;
71
72end
73
74