Manually writing a function matrixpower() in R Problem 1 - Matrix powers in R
  
  R does not have a built-in command for taking matrix powers. 
  
  Write a function matrixpower() with two arguments mat and k that  will
  take integer powers k of a matrix mat.


My attempted solution.

matrixMul &lt;- function(mat1, mat2)
{
    rows &lt;- nrow(mat1)
    cols &lt;- ncol(mat2)

    if(rows == cols)
    {
        matOut &lt;- matrix(nrow = rows, ncol = cols) # empty matrix

        for (i in 1:rows) 
        {
            for(j in 1:cols)
            {
                vec1 &lt;- mat1[i,]
                vec2 &lt;- mat2[,j]

                mult1 &lt;- vec1 * vec2

                matOut[i,j] &lt;- sum(mult1)
            }
        }

        return(matOut)
    }
    else
    {
        return (matrix( rep( 0, len=25), nrow = 5))
    }
}


matrixpower&lt;-function(mat1, k)
{
    pow1 &lt;- abs(k)

    rows &lt;- nrow(mat1)
    cols &lt;- ncol(mat1)

    matOut &lt;- diag(1, rows, cols)

    if(pow1 == 0)
    {
        return(matout)
    }
    if (pow1 == 1)
    {
        matOut &lt;- mat1 
    }

    if(pow1 &gt; 1)
    {
        for (i in 1:pow1) 
        {
            matOut &lt;- matrixMul(matOut, mat1)
        }
    }

    if(k &lt; 0)
    {
        matOut &lt;- solve(matOut)
    }

    return (matOut) 
}

mat1 &lt;- matrix(c(1,2,3,4), nrow = 2, ncol=2)
pow1 &lt;- matrixpower(mat1, -2)
pow1 


I have a few questions here.


Is there any room for improvement in this code?
Does this problem ask for manual implementation of multiplication? Or, should the use of %*% suffice?
It would be more efficient to use binary exponentiation.

Suppose that you want to raise an n by n matrix to the \$k^{th}\$ power.

The current method requires that you do a normal matrix multiplication \$k-1\$ times.

This of course has complexity \$k\$ multiplied by \$f(n)\$, Where \$f(n)\$ is the complexity of a matrix multiplication ( This is usually \$n^ 3\$ unless you write some fancy shmancy code that no one writes)

If you use binary exponentiation you reduce the number of multiplications to \$log(k)\$. Specifically the number of multiplications is the ceiling of \$log_2(k)\$ plus the number of 1 bits in the binary representation of \$k\$.

This is of course much more efficient for large values of \$k\$.