Skip to main content

Matrix Power

Find matrix raised to a particular power.


function mat_power(a,n)
{
  //Logic
  n = parseInt(n);
  c = Array(a.length).fill(0).map(x => Array(a[0].length).fill(0));
  if(n === 0)
  {
    for(var i = 0; i < a.length; i++)
    {
      c[i][i] = 1;
    }
    return c;
  }
  if(n % 2 === 0)
  {
    return mat_power(c = mat_multiply(a, a), n / 2);
  }
  else
  {
    //Refer to Matrix Multiplication Post for details of the function
    return mat_multiply(a, c = mat_power(c = mat_multiply(a, a), n / 2));
  }
}