1 function makeEmptyMatrix(rows, columns)
3 var result = new Array(rows);
4 for (var i = 0; i < rows; ++i)
5 result[i] = new Float32Array(columns);
7 result.columns = columns;
11 function multiplyMatrices(left, right)
13 if (left.columns != right.rows) {
15 "Left matrix has " + left.columns + " columns while right matrix has " +
16 right.rows + " rows.");
19 var result = makeEmptyMatrix(left.rows, right.columns);
21 for (var row = 0; row < result.rows; ++row) {
22 for (var column = 0; column < result.columns; ++column) {
23 for (var i = 0; i < left.columns; ++i)
24 result[row][column] += left[row][i] * right[i][column];
31 function checkMatricesEqual(left, right)
33 if (left.columns != right.columns) {
35 "Left matrix has " + left.columns + " columns while right matrix has " +
36 right.columns + " columns");
38 if (left.rows != right.rows) {
40 "Left matrix has " + left.rows + " rows while right matrix has " +
41 right.rows + " rows");
44 for (var row = 0; row < left.rows; ++row) {
45 for (var column = 0; column < left.columns; ++column) {
46 if (left[row][column] != right[row][column]) {
48 "left[" + row + "][" + column + "] = " + left[row][column] +
49 " while right[" + row + "][" + column + "] = " + right[row][column]);
55 function parseMatrix(string)
59 string.split("\\").forEach(function(string){
61 string.split(" ").forEach(function(string){
62 if (string.match(/^ *$/))
64 row.push(parseFloat(string));
67 if (columns != row.length) {
69 "Not all rows have the same number of columns. First row has " +
70 columns + " columns, while column #" + (result.length + 1) + " has " +
71 row.length + " columns.");
75 var typedRow = new Float32Array(row.length);
76 for (var i = 0; i < columns; ++i)
78 result.push(typedRow);
80 result.rows = result.length;
81 result.columns = columns;
85 function printMatrix(matrix)
89 for (var row = 0; row < matrix.rows; ++row) {
90 for (var column = 0; column < matrix.columns; ++column)
91 maxCellSize = Math.max(maxCellSize, ("" + matrix[row][column]).length);
96 var result = "" + value;
97 while (result.length < maxCellSize)
98 result = " " + result;
102 for (var row = 0; row < matrix.rows; ++row) {
104 for (var column = 0; column < matrix.columns; ++column) {
107 rowText += pad(matrix[row][column]);
113 var left = parseMatrix("1 2 3 4 5 \\ 6 7 8 9 10 \\ 21 22 23 24 25 \\ 26 27 28 29 30");
114 var right = parseMatrix("11 12 31 32 \\ 13 14 33 34 \\ 15 16 35 36 \\ 17 18 37 38 \\ 19 20 39 40");
115 var expectedResult = parseMatrix("245 260 545 560 \\ 620 660 1420 1460 \\ 1745 1860 4045 4160 \\ 2120 2260 4920 5060");
117 for (var i = 0; i < 3000; ++i)
118 checkMatricesEqual(multiplyMatrices(left, right), expectedResult);