最近尝试将一个MATLAB程序通过codegen编译成C++库调用,好不容易编译通过但是运行结果不对,一步步跟踪下来发现是eig函数的问题,记录一下。
现象如同这个例子Matlab Codgen eig() function - strange behaviour。原本在MATLAB中工作正常的程序,编译成库后由于eig函数的结果出现了不同的排序方式和符号,导致最终的错误。例子中的回答也给出了解决方法:手动再对特征值和特征向量进行规范化处理——
1.Normalize all eigenvectors to length 1 (example: [-0.4472,-0.4472,-0.4472,0.4472,0.4472]’ instead of [-1,-1,-1,1,1]‘). Could be achieved using b=bsxfun(@rdivide,b,sqrt(sum(b.^2,1))).
2.For each eigenvectors with a negative value in the first component, take the negative value. (example: [0.4472,0.4472,0.4472,-0.4472,-0.4472]’ instead of [-0.4472,-0.4472,-0.4472,0.4472,0.4472]'). Could be achieved using b=bsxfun(@times,sign(b(1,:)),b).
3.Sort eigenvectors and eigenvalues in ascending order of the eigenvalues.
[V,D] = eig(A)