Skip to content

(second round) creating a certain type of matrix

2 messages · Taka Matzmoto, Adaikalavan Ramasamy

#
Hi R users
Here is what I got with help from Petr Pikal (Thanks Petr Pikal). I modified 
Petr Pikal's code to a little
to meet my purpose.

I created a function to generate a matrix

generate.matrix<-function(n.variable)
{
mat<-matrix(0,n.variable,(n.variable/2)/5+1) #matrix of zeroes
dd<-dim(mat) # actual dimensions
mat[1:(dd[1]/2),1]<-1 #put 1 in first half of first column
mat[((dd[1]/2)+1):dd[1],1]<-rnorm(dd[1]/2,0,1) #put random numbers in 
following part of the matrix column 1
mat[((dd[1]/2)+1):((dd[1]/2)+5),2]<-rnorm(5,0,1) #put random numbers in 
column2
for (i in 3:(dd[2]))
    {
        length.of.rand.numbers <- 5
        my.rand.num<- rnorm(length.of.rand.numbers, 0,1)
        start <- dd[1]/2+5*(i-2)+1
        end <- start + length.of.rand.numbers-1
        mat[((start):end), i]<- my.rand.num
    }
mat
}

Do you (any R users) have any suggestion to this function to make this 
function work better or efficiently?

Taka
It works but I
#
I cleaned up your function a bit but please double check

 generate.matrix <- function(nr, runs=5){

   h   <- nr/2                                ## half of nr
   nc  <- nr/10 + 1

   mat <- matrix(0, nr, nc)                   ## initialize
   
   mat[ ,1] <- c( rep(1, h), rnorm(h) )       ## 1st column
   mat[ (h+1):(h+5), 2] <- rnorm(5)           ## 2nd column
  
   if( nc > 3 ){
    for (i in 3:nc){                          ## column 3 - end
    
      start <-  h + 5*(i-2) + 1
      end   <-  start + runs - 1
    
      mat[ start:end, i] <- rnorm( runs )    
    }
   }
   return(mat)
 } 


However you can simplify this greatly. If you ignore the first column
(which looks like some initialisation column in simulation process),
then you have a matrix with nr/2 rows and nr/10 columns with diagonal
blocks 5 runs filled with rnorm values. Here is what I propose :


 gen.mat <- function(x, runs=5){

   if( (x %% 2*runs)!=0 ) stop(x, " is not a multiple of ", 2*runs)

   nr  <- x/2                   
   nc  <- x/(2*runs)

   mat <- matrix(0, nr, nc)  
   for (i in 1:nc) mat[ ((i-1)*runs + 1) : (i*runs), i ] <- rnorm(runs)
  
   down <- cbind( rnorm(nr), mat )
   top  <- cbind( 1, matrix( 0, nr=nr, nc=nc ) )
   out  <- rbind( top, down )
  
   return(out)
 }

# Examples 
 gen.mat(50)
 gen.mat(55)         ## should generate an error
 gen.mat(24, runs=6)


Does this function do what you want to ?

Regards, Adai
On Tue, 2006-02-07 at 11:03 -0600, Taka Matzmoto wrote: