[R] How to build a large identity matrix faster?

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Jun 7 12:26:09 CEST 2012


On 07/06/2012 10:27, Rui Barradas wrote:
> Hello,
>
> To my great surprise, on my system, Windows 7, R 15.0, 32 bits, an R
> version is faster!

Faster than what? diag() is written entirely in R, just more general 
than yours and so one would expect it to be slower.

I have to say that we don't see a fast identity as a priority, as it 
almost always can be eliminated from calculations, and for large 
matrices one would want to use a sparse representation such as package 
Matrix.

>
>
> Rdiag <- function(n){
> m <- matrix(0, nrow=n, ncol=n)
> m[matrix(rep(seq_len(n), 2), ncol=2)] <- 1
> m
> }
>
> Rdiag(4)
>
> n <- 5e3
> t1 <- system.time(d1 <- diag(n))
> t2 <- system.time(d2 <- Rdiag(n))
> all.equal(d1, d2)
> rbind(diag=t1, Rdiag=t2, ratio=t1/t2)
>
>
> Anyway, why don't you create it once, save a copy and use it many times?
>
> Hope this helps,
>
> Rui Barradas
>
> Em 07-06-2012 08:55, Ceci Tam escreveu:
>> Hello, I am trying to build a large size identity matrix using diag().
>> The
>> size is around 23000 and I've tried diag(23000), that took a long time.
>> Since I have to use this operation several times in my program, the
>> running
>> time is too long to be tolerable. Are there any alternative for diag(N)?
>> Thanks
>>
>> Cheers,
>> yct
>>
>> [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list