JS實現(xiàn)簡單的二維矩陣乘積運算
更新時間:2016年01月26日 10:22:50 作者:m1870164
這篇文章主要介紹了JS實現(xiàn)簡單的二維矩陣乘積運算方法,涉及JavaScript基于數(shù)組操作實現(xiàn)矩陣運算的功能,需要的朋友可以參考下
本文實例講述了JS實現(xiàn)簡單的二維矩陣乘積運算方法。分享給大家供大家參考,具體如下:
Console控制臺截圖如下:

(上圖為輸出結(jié)果直接上代碼了(A矩陣可以乘以B矩陣的前提是A矩陣的列數(shù)等于B矩陣的行數(shù))
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
</head>
<body>
</body>
<script type="text/javascript">
function log(msg) {
console.log(msg);
}
/**
* 可視化的打印出矩陣的數(shù)據(jù)
*/
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) {
// 這里必須傳一個二維數(shù)組,最好嚴格檢驗一下
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矩陣沒有足夠的列數(shù)相乘,轉(zhuǎ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>
更多關(guān)于JavaScript運算相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript數(shù)學(xué)運算用法總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
相關(guān)文章
瀑布流的實現(xiàn)方式(原生js+jquery+css3)
這篇文章主要為大家詳細介紹了原生js+jquery+css3實現(xiàn)瀑布流的相關(guān)代碼,三種實現(xiàn)瀑布流的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-07-07
layer頁面跳轉(zhuǎn),獲取html子節(jié)點元素的值方法
今天小編就為大家分享一篇layer頁面跳轉(zhuǎn),獲取html子節(jié)點元素的值方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09
javascript事件函數(shù)中獲得事件源的兩種不錯方法
許多情況我們需要獲得事件源對象來對其屬性進行更改,在事件響應(yīng)函數(shù)中獲得事件源的方法有如下兩種2014-03-03

