Logo

SQL Server MATRIX Function

Updated 2024-03-28 19:05:40.297000

Description

Use the table-valued function MATRIX to convert the string representation of a matrix into 3rd-normal form.

Syntax

SELECT * FROM [westclintech].[wct].[MATRIX] (
   <@M, nvarchar(max),>)

Arguments

@M

the string representation of the matrix where column values are comma-delimited and rows are semi-colon delimited.

Return Type

table

colNamecolDatatypecolDesc
RowNumintThe zero-based row index for the matrix
ColNumintThe zero-based column index for the matrix
ItemValuefloatThe value at RowNum, ColNum

Remarks

If the array contains NULL, then NULL will be returned.

The function returns an error if the array contains a non-numeric value.

Examples

DECLARE @M as nvarchar(max) = '1,2,3,4,5,6,7;8,9,10,11,12,13,14;15,16,17,18,19,20,21;22,23,24,25,26,27,28'

SELECT *
FROM wct.Matrix(@M)

This produces the following result.

RowNumColNumItemValue
001
012
023
034
045
056
067
108
119
1210
1311
1412
1513
1614
2015
2116
2217
2318
2419
2520
2621
3022
3123
3224
3325
3426
3527
3628

In this example we take the reciprocal the @M matrix, calculate the cross-product , calculate its inverse and pivot the resultant table.

SET @M = wct.MUPDATE(1,NULL,NULL,NULL,NULL,'/',@M,NULL,NULL,NULL,NULL)

SELECT [0],[1],[2],[3]
FROM wct.Matrix(wct.MATMULT(@M,wct.TRANSPOSE(@M)))d
PIVOT (MAX(itemvalue) FOR ColNum in ([0],[1],[2],[3]))pvt
ORDER BY RowNum

This produces the following result.

0123
1.51179705215420.2763074227359940.1570757689040530.110049752793024
0.2763074227359940.06419878684634760.03784411507211150.0269209178215389
0.1570757689040530.03784411507211150.02243497860862580.0159977205709664
0.1100497527930240.02692091782153890.01599772057096640.0114191282392253