First Commit
This commit is contained in:
49
Matrix.js
Normal file
49
Matrix.js
Normal file
@@ -0,0 +1,49 @@
|
||||
|
||||
import Vector from "./Vector.js"
|
||||
|
||||
function random() {
|
||||
let seed = 12345; // fixed seed
|
||||
|
||||
return function() {
|
||||
seed = ( seed * 16807 ) % 2147483647;
|
||||
return ( seed - 1 ) / 2147483646;
|
||||
};
|
||||
}
|
||||
|
||||
const randomFix = random();
|
||||
|
||||
export default class Matrix {
|
||||
constructor( rows, cols, fillValue = 0 ) {
|
||||
this.rows = rows;
|
||||
this.cols = cols;
|
||||
this.data = new Array( rows );
|
||||
for ( let i = 0 ; i < rows ; i++ ) {
|
||||
this.data[ i ] = new Array( cols );
|
||||
for ( let j = 0 ; j < cols ; j++ ) {
|
||||
this.data[ i ][ j ] = fillValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static random( rows, cols, scale = 0.1 ) {
|
||||
const mat = new Matrix( rows, cols );
|
||||
for ( let i = 0 ; i < rows ; i++ ) {
|
||||
for ( let j = 0 ; j < cols ; j++ ) {
|
||||
mat.data[ i ][ j ] = ( randomFix() - 0.5 ) * scale;
|
||||
}
|
||||
}
|
||||
return mat;
|
||||
}
|
||||
|
||||
static matVecMul( mat, vec ) {
|
||||
const result = new Vector( mat.rows );
|
||||
for ( let i = 0 ; i < mat.rows ; i++ ) {
|
||||
let sum = 0;
|
||||
for ( let j = 0 ; j < mat.cols ; j++ ) {
|
||||
sum += mat.data[ i ][ j ] * vec.data[ j ];
|
||||
}
|
||||
result.data[ i ] = sum;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user