matrix operations
by Richard Hunter
JavaScript
const A = [
[1, 2],
[3, 4]
];
const B = [
[5, 6],
[0, -2]
];
const C = [
[2, 5],
[1, 7]
];
// associative law
//log(m(m(A, B), C));
//log(m(A, m(B, C)));
// left distributive law
//log(m(A, a(B, C)));
//log(a(m(A,B), m(A, C)));
// right distributive law
//log(m(a(B, C), A));
//log(a(m(B, A), m(C, A)));
//
const k = 2;
log(sc(k, m(A, B)))
log(m(sc(k, A), B));
log(m(A, sc(k, B)));
function m(rows, B) {
const result = [];
const cols = rowToCols(B);
for (let i = 0; i < rows.length; i++) {
result[i] = [];
const row = rows[i];
for (let j = 0; j < cols.length; j++) {
const col = cols[j];
let temp = 0;
for (let k = 0; k < col.length; k++) {
temp += row[k] * col[k];
}
result[i][j] = temp;
}
}
return result;
}
function a(A, B) {
const result = [];
for (let i = 0; i < A.length; i++) {
const row = A[i];
result[i] = [];
for (let j = 0; j < row.length; j++) {
result[i][j] = A[i][j] + B[i][j];
}
}
return result;
}
function sc(k, M) {
const result = [];
for (let i = 0; i < M.length; i++) {
const row = M[i];
result[i] = [];
for (let j = 0; j < row.length; j++) {
result[i][j] = k * M[i][j];
}
}
return result;
}
function rowToCols(rows) {
const cols = [];
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
for (let j = 0; j < row.length; j++) {
if (!cols[j]) cols[j] = [];
cols[j][i] = row[j];
}
}
return cols;
}
function log(text) {
console.log(text);
}