Example: Singular Value Decomposition of a Matrix
The singular value decomposition of a matrix is performed. The rank of the matrix is also computed.
using System;
using Imsl.Math;
public class SVDEx1
{
public static void Main(String[] args)
{
double[,] a = {
{1, 2, 1, 4},
{3, 2, 1, 3},
{4, 3, 1, 4},
{2, 1, 3, 1},
{1, 5, 2, 2},
{1, 2, 2, 3}
};
// Compute the SVD factorization of A
SVD svd = new SVD(a);
// Print U, S and V.
new PrintMatrix("U").SetPageWidth(80).Print(svd.GetU());
new PrintMatrix("S").SetPageWidth(80).Print(svd.GetS());
new PrintMatrix("V").SetPageWidth(80).Print(svd.GetV());
// Find the rank of A.
int rank = svd.Rank;
Console.Out.WriteLine("rank = " + rank);
}
}
Output
U
0 1 2
0 -0.380475586320569 0.119670992640587 0.439082824383239
1 -0.403753713172442 0.345110837105607 -0.0565761852901658
2 -0.545120486248343 0.429264893493195 0.0513926928086694
3 -0.264784294004146 -0.0683195253271513 -0.883860867430429
4 -0.446310112301556 -0.816827623278282 0.141899675060401
5 -0.354628656614145 -0.102147399162125 -0.00431844397986985
3 4 5
0 -0.565399585908374 0.0243115161463761 -0.57258686109915
1 0.214775576522681 0.80890058872827 0.11929741721493
2 0.432144162809737 -0.572327648171096 0.0403309248707933
3 -0.215253698182974 -0.0625209225900579 -0.30621669907105
4 0.321269584269887 0.0621337820958098 -0.0799352679998222
5 -0.545800221853259 -0.0987946265624981 0.745739576113111
S
0
0 11.4850179115597
1 3.2697512144125
2 2.65335616200783
3 2.08872967244092
V
0 1 2
0 -0.444294128842354 0.555531257799947 -0.435378966673942
1 -0.558067238190387 -0.654298740112323 0.277456900458814
2 -0.32438610320628 -0.351360645592513 -0.732099533429598
3 -0.621238553843379 0.37393031038343 0.444401954223745
3
0 0.55175438744187
1 0.428336065179864
2 -0.485128463324533
3 -0.526066236587424
rank = 4
Link to C# source.