Problem in calculating SVD usung JAVA package

C

ckumar

Hai,

I downloaded two packages JAMA and Matrix Toolkit
for Java(MTJ) from http://math.nist.gov/javanumerics/#libraries.

I calculated Singular Vector Decomposition using these
packages. On decomposing the input matrix(X) we will get three matrices

U - Left Singular Matrix
S - Singular values
V - Right singular Matrix

then X=U*S*(VTranspose).

This works fine for JAMA. But in MTJ I not able to get back the input
matrix on multiplying these three matrices.

I downloaded MTJ from following site
http://www.math.uib.no/~bjornoh/mtj/

I like to know whether the problem is in package or in my code.

Regards,
ackumar

Code using MTJ package:

import mt.*;
import mt.fact.*;
import java.io.*;
import java.lang.*;

class mtjSVD{
public static void main(String args[])
{
double[][] array={{1.0,2.0},{1.0,1.0},{1.0,3.0}};
DenseMatrix X=new DenseMatrix(array);
System.out.println("Rows="+X.numRows()+"\nCols="+X.numColumns());
System.out.println("\n********************\tX\t*******************\n");
printMatrix(X);

SingularvalueComputer svc=new
SingularvalueComputer(X.numRows(),X.numColumns(),true);
SVD svd=new SVD(X.numRows(),X.numColumns());
try{
svd=svc.factor(X.copy());
}catch(Exception ee){ee.printStackTrace();}

DenseMatrix U=svd.getU();
System.out.println("********************\tU\t*******************\n");
printMatrix(U,5);

DenseMatrix V=svd.getVt();
System.out.println("********************\tV\t*******************\n");
printMatrix(V,5);

DenseMatrix S = new DenseMatrix(X.numRows(),X.numColumns());
double singVal[]=svd.getS();
int len=singVal.length;
System.out.println("No. of singular values===> "+len);
for(int i=0;i<len;i++)
S.set(i,i,singVal);
System.out.println("********************\tS\t*******************\n");
printMatrix(S);

System.out.println("********************\tRetained -
X\t*******************\n");
DenseMatrix retainedX=new DenseMatrix(X.numRows(),X.numColumns());
retainedX=(DenseMatrix)U.mult(S,retainedX);
retainedX=(DenseMatrix)retainedX.mult(V.transpose(),retainedX);
printMatrix(retainedX);

}

static void printMatrix(Matrix M)
{
for(int i=0;i<M.numRows();i++)
{
for(int j=0;j<M.numColumns();j++)
{
System.out.print(M.get(i,j)+"\t");
}
System.out.println("\n");
}
}

static void printMatrix(Matrix M,int val)
{
for(int i=0;i<M.numRows();i++)
{
for(int j=0;j<M.numColumns();j++)
{
System.out.print((Double.toString(M.get(i,j))).substring(0,val)+" ");
}
System.out.println("\n");
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top