Jordi 45454 - 1 year ago 99
Javascript Question

Multiply 2 matrices in Javascript

I'm doing a function that multiplies 2 matrices. The matrices will always have the same number of rows and columns. (2x2, 5x5, 23x23, ...)

When I print it, it doesn't work. Why?

For example, if I create two 2x2 matrices:

matrixA:

``````[1][2]

[3][4]
``````

matrixB:

``````[5][6]

[7][8]
``````

The result should be:

``````[19][22]

[43][50]
``````

(http://ncalculators.com/matrix/2x2-matrix-multiplication-calculator.htm)

But, I get:

``````[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``````

You're getting confused with your various temporary arrays. The `undefined` values are caused by out-of-bounds access on the line below your innermost loop.

I recommend that you stick to making a single array for the result of the multiplication. As you're probably aware, the hitch is that JavaScript doesn't allow you to initialize a multi-dimensional array. To make a two-dimensional array, you have to initialize a one-dimensional array, then iterate over its elements and initialize each one to a one-dimensional array.

``````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('&nbsp;&nbsp;'+m[r].join(' ')+'<br />');
}
}

var a = [[8, 3], [2, 4], [3, 6]],
b = [[1, 2, 3], [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));``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download