This tutorial shows how to calculate the largest eigenvalues of a matrix using Lanczos' method.
The Lanczos method is particularly attractive for use with large, sparse matrices, since the only requirement on the matrix is to provide a matrix-vector product. Although less common, the method is sometimes also used with dense matrices.
We start with including the necessary headers:
#include <iostream>
#include <iostream>
#include <string>
#include <iomanip>
We read a sparse matrix from a matrix-market file, then run the Lanczos method. Finally, the computed eigenvalues are printed.
Create the sparse matrix and read data from a Matrix-Market file:
std::vector< std::map<unsigned int, ScalarType> > host_A;
{
std::cout << "Error reading Matrix file" << std::endl;
return EXIT_FAILURE;
}
Create the configuration for the Lanczos method. All constructor arguments are optional, so feel free to use default settings.
Run the Lanczos method for computing eigenvalues by passing the tag to the routine viennacl::linalg::eig().
std::cout << "Running Lanczos algorithm (eigenvalues only). This might take a while..." << std::endl;
Re-run the Lanczos method, this time also computing eigenvectors. To do so, we pass a dense matrix for which each column will ultimately hold the computed eigenvectors.
std::cout << "Running Lanczos algorithm (with eigenvectors). This might take a while..." << std::endl;
Print the computed eigenvalues and exit:
for (std::size_t i = 0; i< lanczos_eigenvalues.size(); i++)
{
std::cout << "Approx. eigenvalue " << std::setprecision(7) << lanczos_eigenvalues[i];
}
return EXIT_SUCCESS;
}
Full Example Code
#include <iostream>
#include <iostream>
#include <string>
#include <iomanip>
{
std::vector< std::map<unsigned int, ScalarType> > host_A;
{
std::cout << "Error reading Matrix file" << std::endl;
return EXIT_FAILURE;
}
10,
30);
std::cout << "Running Lanczos algorithm (eigenvalues only). This might take a while..." << std::endl;
std::cout << "Running Lanczos algorithm (with eigenvectors). This might take a while..." << std::endl;
for (std::size_t i = 0; i< lanczos_eigenvalues.size(); i++)
{
std::cout << "Approx. eigenvalue " << std::setprecision(7) << lanczos_eigenvalues[i];
}
return EXIT_SUCCESS;
}