Ways around pinv([inf])=NaN in Octave/Matlab

蹲街弑〆低调 提交于 2019-12-11 08:07:18

问题


I am using Octave 3.8.1, a Matlab-like program. I'd like to generalize 1/x to the case where x may be a scalar or a matrix. Replacing 1/x with inv(x) or pinv(x) works for most x, except:

octave:1> 1/inf
ans = 0

octave:2> pinv([inf])
ans = NaN

octave:3> inv([inf])
warning: inverse: matrix singular to machine precision, rcond = 0
ans = Inf

Should I convert NaN to 0 afterwards to get this to work? Or have I missed something? Thanks!


回答1:


The Moore–Penrose pseudo inverse, which is the basis for Matab and octave's pinv, is implemented via completely different algorithm than the inv function. More specifically, singular value decomposition is used, which require's finite-valued matrices (they also can't be sparse). You didn't say if your matrices are square or not. The real use of pinv is for solving non-square systems (over- or underdetermined).

However, you shouldn't be using pinv or inv for your application, no matter the dimension of your matrices. Instead you should use mldivide (octave, Matlab), i.e., the backslash operator, \. This is much more efficient and numerically robust.

A1 = 3;
A2 = [1 2 1;2 4 6;1 1 3];
A1inv = A1\1
A2inv = A2\eye(size(A2))

The mldivide function handles rectangular matrices too, but you will get different answers for underdetermined systems compared to pinv because the two use different methods to choose the solution.

A3 = [1 2 1;2 4 6]; % Underdetermined
A4 = [1 2;2 4;1 1]; % Overdetermined
A3inv = A3\eye(min(size(A3))) % Compare to pinv(A3), different answer
A4inv = A4\eye(max(size(A4))) % Compare to pinv(A4), same answer

If you run the code above, you'll see that you get a slightly different result for A3inv as compared to what is returned by pinv(A3). However, both are valid solutions.



来源:https://stackoverflow.com/questions/28466632/ways-around-pinvinf-nan-in-octave-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!