C++ calls the Matlab function to find the eigenvalues
- 2020-06-19 11:03:02
- OfStack
Recently, the mixing of C++ and Matlab is needed to record 1 learning process.
To achieve is to call Matlab function to find the minimum k eigenvalues and their eigenvectors before the matrix.
//C++
#include "engine.h" // use Matlab The header file that the engine needs to include
#include <iostream>
using namespace std;
int main()
{
Engine *m_engine; // create Matlab engine
m_engine = NULL; // Initialization engine
if((!m_engine && !(m_engine = engOpen(NULL)))) // Turn on the engine and it will turn on 1 a Matlab Command line window
{
return -1;
}
engSetVisible(m_engine,1); // Make the command line window visible
char buffer[255]; // Record debugging information for easy debugging
engOutputBuffer(m_engine, buffer, 255);
double A[3][3] = {-1,1,0,
-4,3,0,
1,0,2};
mxArray* AObj = mxCreateDoubleMatrix(3, 3, mxREAL); // create Matlab The size of the matrix 3*3 The real number)
memcpy(mxGetPr(AObj), A, 3*sizeof(double)); // will C++ Incoming data of Matlab In the
engPutVariable(m_engine, "A", AObj); // will AObj The value is assigned to A
engEvalString(m_engine, "cd('E:\\MatlabScripts')"); // Enter the Matlab Path to code
// call Matlab Functions defined in" computeEigens The file name and the function name are required 1 , namely" computeEigens.m "
int k = 2;
engEvalString(m_engine, "[eigVector,eigValue] = computeEigens(A, k);");
// Store calculation results
engEvalString(m_engine,"save('E:\\eigVec_eigV.mat','eigVector','eigValue');");
printf("%s", buffer);
mxDestroyArray(AObj); // The destruction Matlab An array of
if (m_engine) // Shut down Matlab engine
{
engClose(m_engine);
m_engine = NULL;
}
return 0;
}
% Of the call Matlab code
%E:\MatlabScripts\computeEigens.m
function [ eigVector, eigValue ] = computeEigens( M, n_Eigens ) %n_Eigens Is the required number of eigenvalues
[EigenVectors,EigenValues] = eig(M);
[sortedEigenValues, index] = sort(diag(EigenValues));
eigValue = sortedEigenValues(1:n_Eigens);
idx = index(1:n_Eigens);
eigVector = EigenVectors(:,idx);
end
Find the eigenvalue of the sparse matrix
Later, it was found that eig could not be used to solve the sparse matrix, and the error of "Error using eig" would be reported. eigs(A, k, sigma) should be used instead. When sigma='sm', it means to find the eigenvalue with the smallest absolute value of the previous k of the sparse matrix A and its eigenvector. Other values of sigma mean: the eigenvalue with the largest absolute value of 'lm'; The eigenvalue with the smallest absolute value of 'sm'; The largest eigenvalue of 'la'; Minimum eigenvalue of 'sa'; Maximum real part of 'lr'; 'sr' minimum real part; The largest imaginary part of 'li'; 'si' minimum imaginary part.