[R] Error in the inverse of a diagonal matrix?

Martyn Plummer plummer at iarc.fr
Mon Feb 14 10:59:36 CET 2000


Arithmetic operations act element-wise on matrices, which is why you
get 1/0 = Inf (NB the "*" operator also acts element-wise, which is why
you need to use the operator "%*%" for matrix multiplication).

To invert a square matrix use the solve() function. If you know that the
matrix is diagonal then it is more efficient to use

diag(1/(diag(x))

Martyn

On 14-Feb-00 Manuel Castejon Limas wrote:
> I´m new to R so maybe this issue has been asked before and I still could not
> read the complete set of past messages sent to the list.
> I found a weird behabiour that I will explain with a simple example. Lets
> consider the following block of commands:
> 
>> x <- diag(c(1,4,10))
>> x
>      [,1] [,2] [,3]
> [1,]    1    0    0
> [2,]    0    4    0
> [3,]    0    0   10
> 
>> invx <- x^-1
>> invx
>      [,1] [,2] [,3]
> [1,]    1  Inf  Inf
> [2,]  Inf 0.25  Inf
> [3,]  Inf  Inf  0.1
> 
> I would really appreciate if the result would have been
>      [,1] [,2] [,3]
> [1,]  1    0    0
> [2,]  0  0.25  0
> [3,]  0    0  0.1
> 
> most of all because
>> x %*% invx
>      [,1] [,2] [,3]
> [1,]  NaN  NaN  NaN
> [2,]  NaN  NaN  NaN
> [3,]  NaN  NaN  NaN
> 
> does not really satisfies me :-)
> 
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list