matlab pinv 实现_在Octave / Matlab中pinv([inf])= NaN的方法

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!

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值