Bazman
Bazman

Reputation: 2150

Matlab using r divide twice in one expression

If I want to calculate:

var(B(k))=sigma^2(X'X+k*I_p)^-1*(X'X)*(X'X+k*I_p)^-1

where sigma and k are constants, I_p is an identity matrix of the correct dimension and X is an n*p matrix

in MATLAB is this the correct syntax?

var_alpha_Ridge=sigma2*(Gamma+lambda)\Gamma\(Gamma+lambda);

where Gamma=(X'X) and lambda=k*eye(p).

Upvotes: 1

Views: 58

Answers (1)

A. Donda
A. Donda

Reputation: 8477

If you want to do it via the / and \ operators, it would be

var_alpha_Ridge=sigma2*(Gamma+lambda)/Gamma\(Gamma+lambda);

However, I'd prefer to precompute the inverse

iGl = inv(Gamma+lambda);
var_alpha_Ridge=sigma2*iGl*Gamma*iGl;

If you are worried about numerical stability, use pinv instead:

iGl = pinv(Gamma+lambda);
var_alpha_Ridge=sigma2*iGl*Gamma*iGl;

Since the matrix you are inverting is probably well-conditioned because of the lambda part, I wouldn't expect large differences between the three ways to compute it.

Upvotes: 1

Related Questions