I'm writing an algorithm with a lot of steps (PCA), and two of them are finding eigenvalues and eigenvectors of a given matrix.
I do not wish to write the whole code for it because I know it is a long job, so I searched for some adhoc code for that but just found 1 or 2 libraries and at first I prefer not to include libraries and I don't want to move to matlab.
Is there any algorithm/tutorial/code that doesn't seem very hard to follow?
1:Finding Eigenvalues and Eigenvectors. Let A be an n×n matrix. First, find the eigenvalues λ of A by solving the equation det(λI−A)=0. For each λ, find the basic eigenvectors X≠0 by finding the basic solutions to (λI−A)X=0.
If someone needs this, here how I did it
Eigen::EigenSolver<Eigen::MatrixXf> eigensolver;
eigensolver.compute(covmat);
Eigen::VectorXf eigen_values = eigensolver.eigenvalues().real();
Eigen::MatrixXf eigen_vectors = eigensolver.eigenvectors().real();
std::vector<std::tuple<float, Eigen::VectorXf>> eigen_vectors_and_values;
for(int i=0; i<eigen_values.size(); i++){
std::tuple<float, Eigen::VectorXf> vec_and_val(eigen_values[i], eigen_vectors.row(i));
eigen_vectors_and_values.push_back(vec_and_val);
}
std::sort(eigen_vectors_and_values.begin(), eigen_vectors_and_values.end(),
[&](const std::tuple<float, Eigen::VectorXf>& a, const std::tuple<float, Eigen::VectorXf>& b) -> bool{
return std::get<0>(a) <= std::get<0>(b);
});
int index = 0;
for(auto const vect : eigen_vectors_and_values){
eigen_values(index) = std::get<0>(vect);
eigen_vectors.row(index) = std::get<1>(vect);
index++;
}
Here covmat in which eigenvectors and eigenvalues to be found out. Also, I sort them according to descending order which we do the most of the times. One important thing is that when you selecting which eigendecomposition technique is to be used to be careful because those are not doing the same way. You may find out more information here [https://eigen.tuxfamily.org/dox/group__Eigenvalues__Module.html ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With