 # SQL Server economy-sized singular value decomposition

SVD

Updated: 05 March 2015

Use the scalar function SVD to calculate the economy-sized singular value decomposition of an m-x-n matrix A. SVD returns an m-x-n orthogonal matrix U, an n-x-n orthogonal matrix V and an n-x-n diagonal matrix W such that,

A = UWVT
SVD expects a string representation of the matrix, with columns separated by commas and rows separated by semi-colons.

Syntax
SELECT [wct].[SVD](
<@Matrix, nvarchar(max),>
,<@MatrixName, nvarchar(4000),>)

Arguments
@Matrix
a string representation of the matrix.
@MatrixName
a string identifying the name of matrix to be returned; 'U','V' or 'W'.

Return Types
[nvarchar](max)

Remarks
·         The string representations of @Matrix must only contain numbers, commas (to separate the columns), and semi-colons to separate the rows.
·         Consecutive commas will generate an error.
·         Consecutive semi-colons will generate an error.
·         Non-numeric data between commas will generate an error.
·         Non-number data between semi-colons will generate an error.
·         To convert non-normalized data to a string format, use the MATRIX2STRING or the MATRIX2STRING_q function.
·         To convert normalized data to a string format, us the NMATRIX2STRING or the NMATRIX2STRING_q function.
·         To convert the string result to a table, us the table-valued function MATRIX.
·         @MatrixName must be either 'U','V' or 'W' or an error message will be generated.
Examples
In this example, we return the L matrix from the LU decomposition.
DECLARE @A as varchar(max) = wct.MATRIX2STRING_q(
'SELECT
*
FROM (
VALUES
(1,2,3,4)
,(2,3,4,5)
,(3,4,5,6)
,(4,5,6,7)
)n(x1,x2,x3,x4)'
)

SELECT
wct.SVD(@A,'U') as U

This produces the folllowing result.

To get the W matrix, we would have entered:
SELECT
wct.SVD(@A,'W') as W

This produces the following result
.

And, to get the V matrix we enter the following:
SELECT
wct.SVD(@A,'V') as V

returning

In this example we calculate UWV' returning the original matrix.
SELECT
,,,
FROM (
SELECT
*
FROM
wctMath.wct.Matrix(
wctMath.wct.MATMULT(
wctMath.wct.MATMULT(
wct.SVD(@A,'U'),wct.SVD(@A,'W')
)
,wctMath.wct.TRANSPOSE(wct.SVD(@A,'V')
)
)
)
) p
PIVOT(SUM(ItemValue)
For ColNum IN(,,,)
) as pvt

This produces the following result.

### Support  Copyright 2008-2023 Westclintech LLC         Privacy Policy        Terms of Service