Skip to content

Instantly share code, notes, and snippets.

@jagedn
Last active May 26, 2020 21:12
Show Gist options
  • Save jagedn/13de1de4303efb023976c162275cd0c8 to your computer and use it in GitHub Desktop.
Save jagedn/13de1de4303efb023976c162275cd0c8 to your computer and use it in GitHub Desktop.
Google Sheet to elevate a matrix to the n power
/*
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;
}
@jagedn
Copy link
Author

jagedn commented May 26, 2020

image

@jagedn
Copy link
Author

jagedn commented May 26, 2020

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment