閱讀wiki article on SVD。以下代碼是代表性的例子的第2節中
import Jama.Matrix;
import Jama.SingularValueDecomposition;
public class JAMATest {
static public void printMatrix(Matrix m){
double[][] d = m.getArray();
for(int row = 0; row < d.length; row++){
for(int col = 0; col < d[row].length; col++){
System.out.printf("%6.4f\t", m.get(row, col));
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
double[][] vals = { {1., 0., 0., 0., 2.},
{0., 0., 3., 0., 0.},
{0., 0., 0., 0., 0.},
{0., 4., 0., 0., 0.}
};
Matrix A = new Matrix(vals);
SingularValueDecomposition svd = new SingularValueDecomposition(A);
System.out.println("A = ");
printMatrix(A);
System.out.println("U = ");
printMatrix(svd.getU());
System.out.println("Sigma = ");
printMatrix(svd.getS());
System.out.println("V = ");
printMatrix(svd.getV());
}
}
,併產生所述outputL:
A =
1.0000 0.0000 0.0000 0.0000 2.0000
0.0000 0.0000 3.0000 0.0000 0.0000
0.0000 0.0000 0.0000 0.0000 0.0000
0.0000 4.0000 0.0000 0.0000 0.0000
U =
0.0000 0.0000 -1.0000 0.0000
0.0000 1.0000 -0.0000 0.0000
0.0000 0.0000 -0.0000 1.0000
1.0000 0.0000 -0.0000 0.0000
Sigma =
4.0000 0.0000 0.0000 0.0000 0.0000
0.0000 3.0000 0.0000 0.0000 0.0000
0.0000 0.0000 2.2361 0.0000 0.0000
0.0000 0.0000 0.0000 0.0000 0.0000
0.0000 0.0000 0.0000 0.0000 0.0000
V =
0.0000 -0.0000 -0.4472 -0.8944 -0.0000
0.0000 -0.0000 -0.0000 -0.0000 -0.0000
0.0000 1.0000 -0.0000 -0.0000 -0.0000
0.0000 -0.0000 -0.0000 -0.0000 1.0000
1.0000 -0.0000 -0.8944 0.4472 -0.0000
希望這有助於。此外,FWIW這裏是Matlab的同樣的問題輸出:
>> A = [1.0000, 0.0000, 0.0000, 0.0000, 2.0000; 0, 0, 3, 0, 0; 0, 0, 0, 0, 0; 0, 4, 0, 0, 0];
>> A
A =
1 0 0 0 2
0 0 3 0 0
0 0 0 0 0
0 4 0 0 0
>> [U, S, V] = svd(A);
>> U
U =
0 0 1 0
0 1 0 0
0 0 0 -1
1 0 0 0
>> S
S =
4.0000 0 0 0 0
0 3.0000 0 0 0
0 0 2.2361 0 0
0 0 0 0 0
>> V
V =
0 0 0.4472 0 -0.8944
1.0000 0 0 0 0
0 1.0000 0 0 0
0 0 0 1.0000 0
0 0 0.8944 0 0.4472
至於第一個問題,下面的代碼不會產生錯誤:
import Jama.Matrix;
public class JAMATest {
/**
* @param args
*/
public static void main(String[] args) {
double[][] vals = {{1.,1.,0},{1.,0.,1.},{1.,3.,4.},{6.,4.,8.}};
Matrix A = new Matrix(vals);
}
}
所以別的東西,你正在做的事情必須引起它有一個例外。嘗試使用我的printMatrix方法代替你正在使用的任何東西,看看它是否有幫助。
感謝您的解決方案。我想用jama運行多重回歸,並有同樣的問題。也許我的問題很奇怪,但我不能編輯SingularValueDecomposition類。這意味着netbeans不允許我編輯jama代碼。 – MTT 2013-06-05 22:54:31