c++matlabmatrixeigen3exponentiation

How to implement scalar raised to the power of a matrix in Eigen?


I have the following code in MATLAB that I wish to port to C++, ideally with the Eigen library:

N(:,i)=2.^L(:,i)+1;

Where L is a symmetric matrix (1,2;2,1), and diagonal elements are all one.

In Eigen (unsupported) I note there is a function to calculate the exponential of a matrix, but none to raise an arbitrary scalar to a matrix power.

http://eigen.tuxfamily.org/dox-devel/unsupported/group__MatrixFunctions__Module.html#matrixbase_exp

Is there something I am missing?


Solution

  • If you really wanted to raise an arbitrary scalar to a matrix power, you should use the identity a^x = exp(log(a)*x). However, the Matlab .^ operator computes an element-wise power. If you want the same in Eigen, use the corresponding Array functionality:

    N.col(i) = pow(2.0, L.col(i).array()) + 1.0;
    

    Beware that Eigen starts indexing at 0, and Matlab starts at 1, so you may need to replace i by i-1.