Created
October 5, 2021 16:20
-
-
Save AnastasiaDunbar/50e7fed6758442886d163f5067cf4d08 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function multiplyMatrix(a,b){ | |
var o=[]; | |
for(var i=0;i<a.length;i++){ | |
o[i]=[]; | |
for(var j=0;j<b[0].length;j++){ | |
var s=0; | |
for(var k=0;k<a.length;k++){s+=a[i][k]*b[k][j];} | |
o[i][j]=s; | |
} | |
} | |
return o; | |
} | |
function invertMatrix(matrix){ | |
//http://blog.acipo.com/matrix-inversion-in-javascript | |
//https://en.wikipedia.org/wiki/Gaussian_elimination | |
if(matrix.length!==matrix[0].length){ | |
throw new RangeError("Matrix must be square"); | |
} | |
var dim=matrix.length,I=[],C=[]; | |
for(let r=0;r<dim;r++){ | |
I[r]=[];C[r]=[]; | |
for(let c=0;c<dim;c++){ | |
I[r][c]=c===r?1:0; | |
C[r][c]=matrix[r][c]; | |
} | |
} | |
for(let i=0;i<dim;i++){ | |
var e=C[i][i]; | |
if(e===0){ | |
for(let ii=i+1;ii<dim;ii++){ | |
if(C[ii][i]!==0){ | |
for(let j=0;j<dim;j++){ | |
e=C[i][j];C[i][j]=C[ii][j];C[ii][j]=e; | |
e=I[i][j];I[i][j]=I[ii][j];I[ii][j]=e; | |
} | |
break; | |
} | |
} | |
e=C[i][i]; | |
if(e===0){return new Error("Not invertible");} | |
} | |
for(let j=0;j<dim;j++){ | |
C[i][j]/=e;I[i][j]/=e; | |
} | |
for(let ii=0;ii<dim;ii++){ | |
if(ii===i){continue;} | |
e=C[ii][i]; | |
for(let j=0;j<dim;j++){ | |
C[ii][j]-=e*C[i][j]; | |
I[ii][j]-=e*I[i][j]; | |
} | |
} | |
} | |
return I; | |
} | |
function addMatrix(a,b){ | |
var o=[]; | |
for(var i=0;i<a.length;i++){ | |
o[i]=[]; | |
for(var j=0;j<a[0].length;j++){ | |
o=a[i][j]+b[i][j]; | |
} | |
} | |
return o; | |
} | |
function transposeMatrix(matrix){ | |
var o=[]; | |
for(var i=0;i<matrix[0].length;i++){ | |
o[i]=[]; | |
for(var j=0;j<matrix.length;j++){ | |
o[i][j]=matrix[j][i]; | |
} | |
} | |
return o; | |
} | |
function identityMatrix(n){ | |
var o=[]; | |
for(var i=0;i<n;i++){ | |
o[i]=[]; | |
for(var j=0;j<n;j++){ | |
o[i][j]=j===i?1:0; | |
} | |
} | |
return o; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment