[R] Building a matrix so that matrix(r, c)<-matrix(c, r) with No For Loops

David Winsemius dwinsemius at comcast.net
Sat Mar 26 19:06:28 CET 2011


On Mar 26, 2011, at 9:44 AM, Brian Pellerin wrote:

> Hello,
>
> I would like to take advantage of the upper.tri() function here but  
> I don't
> know exactly. Here is some working code...
> i<-5
> fi<-matrix(0,nrow=i,ncol=i)
> for(r in 1:i){
> for(c in 1:i){
> if(r==c){
> fi[r,c]<-1
> }else if(r<c){
> fi[r,c]<-1-runif(1)^.5
> }else{
> fi[r,c]<-fi[c,r]
> }
> }
> }
>
> So far I know I can simplify this code to 5 lines (no for loops):
> i<-5
> fi<-matrix(nrow=i,ncol=i)
> fi[upper.tri(fi)]<-1-runif(length(fi[upper.tri(fi)]))^.5
> diag(fi)<-1
> fi[lower.tri(fi)]<-fi[upper.tri(fi)]#This entry is not correct.  
> fi[r,c] ! ==
> fi[c,r]

I've always found using the upper.tri and lower.tri functions error  
prone in my hands, because they are really logical matrices for  
selection rather than returning values as I naively expect. Try this:

i<-5
fi<-diag(1,i,i)
fi[upper.tri(fi)]<-1-runif(length(fi[upper.tri(fi)]))^.5
fi[lower.tri(fi)]<-t(fi)[lower.tri(fi)]
fi

It may seem odd to use lower.tri(fi) inside `[ ]` since the values of  
`fi` in the lower triangle are all zero, but you are really just using  
it to extract from `t(fi)`.

-- 
David.

>
> Any suggestions?
>
> Sincerely,
> Brian
>
> 	[[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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list