60 lines
1.7 KiB
Plaintext
60 lines
1.7 KiB
Plaintext
/* Matrix transposition, multiplication, identity, and exponentiation, in Jsish */
|
|
function Matrix(ary) {
|
|
this.mtx = ary;
|
|
this.height = ary.length;
|
|
this.width = ary[0].length;
|
|
}
|
|
|
|
Matrix.prototype.toString = function() {
|
|
var s = [];
|
|
for (var i = 0; i < this.mtx.length; i++) s.push(this.mtx[i].join(","));
|
|
return s.join("\n");
|
|
};
|
|
|
|
// returns a transposed matrix
|
|
Matrix.prototype.transpose = function() {
|
|
var transposed = [];
|
|
for (var i = 0; i < this.width; i++) {
|
|
transposed[i] = [];
|
|
for (var j = 0; j < this.height; j++) transposed[i][j] = this.mtx[j][i];
|
|
}
|
|
return new Matrix(transposed);
|
|
};
|
|
|
|
// returns a matrix as the product of two others
|
|
Matrix.prototype.mult = function(other) {
|
|
if (this.width != other.height) throw "error: incompatible sizes";
|
|
|
|
var result = [];
|
|
for (var i = 0; i < this.height; i++) {
|
|
result[i] = [];
|
|
for (var j = 0; j < other.width; j++) {
|
|
var sum = 0;
|
|
for (var k = 0; k < this.width; k++) sum += this.mtx[i][k] * other.mtx[k][j];
|
|
result[i][j] = sum;
|
|
}
|
|
}
|
|
return new Matrix(result);
|
|
};
|
|
|
|
// IdentityMatrix is a "subclass" of Matrix
|
|
function IdentityMatrix(n) {
|
|
this.height = n;
|
|
this.width = n;
|
|
this.mtx = [];
|
|
for (var i = 0; i < n; i++) {
|
|
this.mtx[i] = [];
|
|
for (var j = 0; j < n; j++) this.mtx[i][j] = (i == j ? 1 : 0);
|
|
}
|
|
}
|
|
IdentityMatrix.prototype = Matrix.prototype;
|
|
|
|
// the Matrix exponentiation function
|
|
Matrix.prototype.exp = function(n) {
|
|
var result = new IdentityMatrix(this.height);
|
|
for (var i = 1; i <= n; i++) result = result.mult(this);
|
|
return result;
|
|
};
|
|
|
|
provide('Matrix', '0.60');
|