class Matrix {
constructor(dims, fill = 0){
this.nrow = dims[0];
this.ncol = dims[1];
this.size = this.nrow*this.ncol;
const vec_fill = fill.length > 1;
if(vec_fill && (fill.length !== this.nrow*this.ncol)){
throw(`Expecting a fill vector of length ${this.size} but got a vector of length ${fill.length}`)
};
this.vals = Float32Array.from(
vec_fill ?
fill:
[...(new Array(this.nrow*this.ncol))].map(d => fill)
);
}
mat_pos(i,j){
return (this.ncol)*i + j
}
set(i,j, val, inplace = true){
if(inplace){
this.vals[this.mat_pos(i,j)] = val
} else {
const newMat = new Matrix([this.nrow, this.ncol], [...this.vals]);
newMat.set(i,j, val);
return newMat
}
}
get(i,j){
return this.vals[this.mat_pos(i,j)]
}
row(i){
const row_res = new Float32Array(this.ncol);
for(let j=0; j<this.ncol; j++) row_res[j] = this.get(i,j);
return row_res;
}
col(j){
const col_res = new Float32Array(this.nrow);
for(let i=0; i<this.nrow; i++) col_res[i] = this.get(i,j);
return col_res;
}
pprint(){
return [...(new Array(this.nrow))].map(
(_,i) => [...(new Array(this.ncol))].map(
(_,j) => this.get(i,j) ))
}
}