本文實例講述了JS實現簡單的二維矩陣乘積運算方法。分享給大家供大家參考,具體如下:
Console控制台截圖如下:
(上圖為輸出結果直接上代碼了(A矩陣可以乘以B矩陣的前提是A矩陣的列數等於B矩陣的行數)
<!DOCTYPE html> <html> <head> <title>demo</title> </head> <body> </body> <script type="text/javascript"> function log(msg) { console.log(msg); } /** * 可視化的打印出矩陣的數據 */ function printMatrixData(data) { console.log(data); if(!data) { return; } var numberSize = 5; for(var i=0, len=data.length; i<len; i++) { var row = data[i]; var rowLog = "("; for(var j=0, jLen=row.length; j<jLen; j++) { rowLog += row[j]; // 補齊空格 rowLog += indent(numberSize - (row[j]+"").length); } rowLog+=")"; console.log(rowLog); } } /** * 拼接指定長度的空格 */ function indent(length) { var empty = ""; for(var i=0; i<length; i++) { empty += " "; } return empty; } /** * 矩陣原型 */ function Matrix(data) { // 這裡必須傳一個二維數組,最好嚴格檢驗一下 if(typeof data !== "object" || typeof data.length === "undefined" || !data) { throw new Error("data's type is error"); } this.data = data; this.cols = data.length; } var M = { findByLocation: function(data, xIndex, yIndex) { if(data && data[xIndex]) { return data[xIndex][yIndex]; } }, // 矩陣乘積 multiply: function(m, n) { if(!m instanceof Matrix && !n instanceof Matrix) { throw new Error("data's type is error"); } var mData = m.data; var nData = n.data; if(mData.length == 0 || nData.length == 0) { return 0; } if(mData[0].length != nData.length) { throw new Error("the two martrix data is not allowed to dot"); } var result = []; for(var i=0, len=mData.length; i<len; i++) { var mRow = mData[i]; result[i] = []; for(var j=0, jLen=mRow.length; j<jLen; j++) { var resultRowCol = 0; // 如果n矩陣沒有足夠的列數相乘,轉入m矩陣下一行 if(typeof this.findByLocation(nData, 0, j) === "undefined") { break; } for(var k=0, kLen=jLen; k<kLen; k++) { resultRowCol += mRow[k]*this.findByLocation(nData, k, j); } result[i][j] = resultRowCol; } } return result; } }; var m = new Matrix([[2, -1], [-2, 1], [-1, 2]]); var n = new Matrix([[4, -3], [3, 5]]); var result = M.multiply(m, n); printMatrixData(result); var m2 = new Matrix([[2, 3, 1], [5, 2, 4], [-3, 2, 0]]); var n2 = new Matrix([[11], [5], [8]]); var result2 = M.multiply(m2, n2); printMatrixData(result2); </script> </html>
更多關於JavaScript運算相關內容感興趣的讀者可查看本站專題:《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。