Skip to content

MDiag

Description

MDiag either creates a square matrix with the desired diagonal, or it extracts the diagonal from a square matrix. If the input is a vector then it creates a square matrix with that vector on the diagonal. If the input is a square matrix, then it extracts the diagonal and returns it as a column vector.

This is a helper function used in a number of other (regression) lambda functions: OLS, WLS, Sres, PolyResids and possibly others in the future.

Syntax

MDiag(X) where X is either a vector (row or column) or a square matrix.

Note that there is no validation of the input. If a nonsquare matrix is passed into this function it will output a square diagonal matrix with the first elements of the input.

Example

MDiag examples: a column or row vector becomes a diagonal matrix; a square matrix gives its diagonal; a 4x3 matrix gives a 4x4 diagonal matrix

Source Code

MDiag = LAMBDA(X, // input is either a square matrix or a row/column vector
    LET(
        numrows, ROWS(X),
        numcols, COLUMNS(X),
        n, MAX(numrows, numcols),
        IF(
            numrows = numcols,
            //convert square matrix to column vector
            INDEX(X, SEQUENCE(numrows), SEQUENCE(numrows)),
            //convert vector to square matrix
            MAKEARRAY(n, n, LAMBDA(numrows, numcols, IF(numrows = numcols, INDEX(TOCOL(X), numrows), 0)))
        )
    )
);