Last active
May 26, 2020 21:12
-
-
Save jagedn/13de1de4303efb023976c162275cd0c8 to your computer and use it in GitHub Desktop.
Google Sheet to elevate a matrix to the n power
This file contains hidden or 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
/* | |
In a Google Sheet select Tools->Script Editor and copy&paste this code and save the file | |
You can use this function in a cell as: | |
=pow_matrix(A5:C7,3) | |
*/ | |
function pow_matrix(a, n) { | |
if( !a.map ) | |
return []; | |
if( a.length != a[0].length ) | |
return "No es cuadrada"; | |
if( n == 1 ){ | |
return a; | |
} | |
var b = []; | |
for(var i=0; i<a.length; i++){ | |
var row = []; | |
for( var j=0; j<a[i].length; j++){ | |
row.push( a[i][j] ); | |
} | |
b.push(row); | |
} | |
for(var v=1; v<n; v++){ | |
var c = []; | |
for(var i=0; i<a.length; i++){ | |
var row = []; | |
for( var j=0; j<a[i].length; j++){ | |
row.push( 0 ); | |
} | |
c.push(row); | |
} | |
for(var i=0; i<a.length; i++){ | |
for( var j=0; j<a[i].length; j++){ | |
c[i][j]=0; | |
for(var k=0; k<a[i].length; k++){ | |
c[i][j]+=a[i][k]*b[k][j] | |
} | |
} | |
} | |
a = c; | |
} | |
return a; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment