我有兩個函數,我用它來遞歸地計算矩陣的行列式。這些值取自HTML表單。但功能不運行。有人能幫助我嗎?我會很感激。Javascript det計算
HTML
<form>
element 0_0 <input type = "text" class = "elements"/>
element 0_1 <input type = "text" class = "elements"/>
element 1_0 <input type = "text" class = "elements"/>
element 1_1 <input type = "text" class = "elements"/>
<input type = "button" value = "clickMe" onclick = "determinant('elements','class')"/>
</form>
的JavaScript
function create2Darray(clname){
var A = document.getElementsByClassName(clname);
var arr = new Array();
var rows = Math.sqrt(A.length);
for(var i = 0; i < rows; i++){
arr[i] = new Array();
for(var j = 0; j < rows;j++){
arr[i][j] = A[i*rows + j].value;
}
}
return arr;
}
function determinant (matrixClass,type) {
if(type == 'class'){
var matrix = create2Darray(matrixClass);
} else if(type == 'name'){
var matrix = new Array();
}
var det = 0;
if (matrix.length == 1){
return matrix[0][0];
} else if (matrix.length == 2){
return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
}
var smaller = new Array();//creating an empty array for a matrix minor;
for (var k = 0; k < matrix.length; k++){
smaller[k] = [];
for(var l = 0;l < matrix.length; l++){
smaller[k][l] = [];
}
}
for (var i = 0; i < matrix.length; i++){
for (a = 1; a < matrix.length; a++) {
for (b = 0; b < matrix.length; b++) {
if (b < i) {
smaller[a - 1][b] = matrix[a][b];
} else if (b > i) {
smaller[a - 1][b - 1] = matrix[a][b];
}
}
}
if (i % 2 == 0) {
s = 1;
} else {
s = -1;
}
det += s * matrix[0][i] * (determinant(smaller,'name'));
}
return det;
alert(det);
}
注:一個問題是這個recursion.I試圖計算並返回和報警矩陣2×2的決定因素,它的工作。但是當我試圖用3x3矩陣做它時沒有。所以請幫助
你真的應該考慮在其他職位的答案不斷開拓新的問題之前! http://stackoverflow.com/questions/16489816/javascript-matrix-inversion – 2013-05-12 12:14:50