我正在做一个乘以2个矩阵的函数.矩阵将始终具有相同的行数和列数. (2×2,5×5,23×23,……)
当我打印它时,它不起作用.为什么?
例如,如果我创建两个2×2矩阵:
矩阵matrixA:
[1][2] [3][4]
matrixB:
[5][6] [7][8]
结果应该是:
[19][22] [43][50]
(http://ncalculators.com/matrix/2×2-matrix-multiplication-calculator.htm)
但是,我得到:
[19][undefined] [22][indefined]
function multiplyMatrix(matrixA,matrixB) { var result = new Array();//declare an array //var numColsRows=$("#matrixRC").val(); numColsRows=2; //iterating through first matrix rows for (var i = 0; i < numColsRows; i++) { //iterating through second matrix columns for (var j = 0; j < numColsRows; j++) { var matrixRow = new Array();//declare an array var rrr = new Array(); var resu = new Array(); //calculating sum of pairwise products for (var k = 0; k < numColsRows; k++) { rrr.push(parseInt(matrixA[i][k])*parseInt(matrixB[k][j])); }//for 3 resu.push(parseInt(rrr[i])+parseInt(rrr[i+1])); result.push(resu); //result.push(matrixRow); }//for 2 }//for 1 return result; }// function multiplyMatrix
解决方法
你对各种临时数组感到困惑.未定义的值是由最内层循环下面的行上的越界访问引起的.
我建议您坚持为乘法结果制作单个数组.您可能已经意识到,遗憾的是JavaScript不允许您初始化多维数组.要制作二维数组,必须初始化一维数组,然后迭代其元素并将每个数组初始化为一维数组.
function multiply(a,b) { var aNumRows = a.length,aNumCols = a[0].length,bNumRows = b.length,bNumCols = b[0].length,m = new Array(aNumRows); // initialize array of rows for (var r = 0; r < aNumRows; ++r) { m[r] = new Array(bNumCols); // initialize the current row for (var c = 0; c < bNumCols; ++c) { m[r][c] = 0; // initialize the current cell for (var i = 0; i < aNumCols; ++i) { m[r][c] += a[r][i] * b[i][c]; } } } return m; } function display(m) { for (var r = 0; r < m.length; ++r) { document.write(' '+m[r].join(' ')+'<br />'); } } var a = [[8,3],[2,4],[3,6]],b = [[1,2,[4,6,8]]; document.write('matrix a:<br />'); display(a); document.write('matrix b:<br />'); display(b); document.write('a * b =<br />'); display(multiply(a,b));