I want to sort eigenvectors by their eigenvalues and I'm using Eigen. I tried the following post (Sorting eigenvectors by their eigenvalues (associated sorting)), but it fails to compile with MS VisualStudio 2015.
So I figure it cannot be that hard. I just need to sort by the eigenvalues, keep track of their old and new order and then resort the eigenvector matrix.
This works well in my test code:
#include <algorithm>
struct a
{
double num1;
int num2;
};
bool acompare(a lhs, a rhs) { return lhs.num1 < rhs.num1; }
int demoSortWithStructure()
{
a array[5];
array[0].num1 = 1;
array[0].num2 = 1;
array[1].num1 = 5;
array[1].num2 = 2;
array[2].num1 = 3;
array[2].num2 = 3;
array[3].num1 = 2;
array[3].num2 = 4;
array[4].num1 = 4;
array[4].num2 = 0;
cout << "before sort" << endl;
for (int i = 0; i < 5; i++)
cout << array[i].num1 << "\t" << array[i].num2 << endl;
std::sort(array, array + 5, acompare);
cout << "\n\nafter sort" << endl;
for (int i = 0; i < 5; i++)
cout << array[i].num1 << "\t" << array[i].num2 << endl;
return 1;
}
So, I went on to generalize the code as follows:
void MyClass::SortEigenValuesAndEigenMatrix(VectorXcd eigenvalue, MatrixXcd eigenvector)
{
VectorXcd eigenvalueOriginal = eigenvalue;
MatrixXcd eigenvectorOriginal = eigenvector;
int noValues = eigenvalue.rows();
a *array = new a[noValues];
for (int iValue = 0; iValue < noValues; iValue++)
{
array[iValue].index = iValue;
array[iValue].valueReal = eigenvalue(iValue).real();
}
sort(array[0],
array[noValues],
acompare);
for (int iValue = 0; iValue < noValues; iValue++)
{
int indexNew = array[iValue].index;
eigenvalue(iValue) = eigenvalueOriginal(indexNew);
eigenvector.col(iValue) = eigenvectorOriginal.col(indexNew);
}
}
For context, my eigenvalues and eigenvectors are defined as complex, but they are real values. So, I just take the real value and intend to sort based upon the real (signed) values.
The compiler throws the following error:
Severity Code Description Project File Line Suppression State
Error C2784 'std::complex<_Other> std::operator -(const _Ty &,const std::complex<_Other> &)': could not deduce template argument for 'const std::complex<_Other> &' from 'a' testRCWA d:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm 3203
I don't understand. How can the compiler be inferring the use of
std::complex
What about my templating is unclear? Am I supposed to explicitly declare the type when using sort? Why does this happen in this code, but not when it is isolated?