[R] elegant matrix creation

Gabor Grothendieck ggrothendieck at myway.com
Wed Jul 28 18:04:34 CEST 2004


Not sure if this qualifies as elegant or not but it (1) does allow one
to generate all three matrices using the same scheme, (2) is 
simple requiring only a single one line function, (3) reduces the number 
of numbers you must specify from 81 to 18 per matrix and (4) gives 
some kminimal insight into the patterns. 

The key observation is that each row of each matrix is a cyclically
shifted version of the first row of that same matrix.  Thus given the 
first row and a vector of shifts we can reconstruct the remaining rows.

Define a function which shifts its vector argument v by shift positions
to the left producing a one row matrix.  If shift is a vector the each
row of the result corresponds to one shift in vector shift.

shiftL <- function(v, shift) 
	outer(shift,seq(along=v)-1, function(i,j)v[(i+j)%%length(v)+1])

# now run shiftL using the first row of each matrix and the shift vector
# for each matrix

jj1 <- shiftL(c(1,1,1,2,2,2,3,3,3),c(0,3,6,0,3,6,0,3,6))
jj2 <- shiftL(c(1,2,1,3,1,3,2,3,2),c(0,6,3,0,6,3,0,6,3))
jj3 <- shiftL(c(1,1,1,2,2,2,3,3,3),c(0,4,8,3,7,2,6,1,5))

or turning the input vectors into expressions themselves:

jj1 <- shiftL( rep(1:3,c(3,3,3)), rep(c(0,3,6),3) )
jj2 <- shiftL( c(shiftL(c(1,3,2),c(0,2,0))), rep(c(0,6,3),3) )
jj3 <- shiftL( rep(1:3,c(3,3,3)), seq(0,32,4) %% 9 )


Robin Hankin <rksh <at> soc.soton.ac.uk> writes:

: 
: Hello everybody.
: 
: I am trying to reproduce a particular matrix in an elegant way.  If I
: have
: 
: jj1 <-
: structure(c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,
: 3,1,2,3,1,2,3,1,2,3,2,3,1,2,3,1,2,3,1,2,3,
: 1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,3,1,2,3,1,
: 2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,
: 2),.Dim = as.integer(c(9,9)))
: 
: [ image(jj1) is good here ] then I can get this with
: 
: kronecker(matrix(1,3,1),kronecker(1+outer(0:2,0:2,"+")%%3,matrix(1,1,3)))
: 
: I want to reproduce the following matrices in an equivalent way:
: 
: jj2 <- matrix(c(1,2,3,1,2,3,1,2,3,2,3,1,2,3,1,2,3,1,
: 1,2,3,1,2,3,1,2,3,3,1,2,3,1,2,3,1,2,1,2,3,1,2,
: 3,1,2,3,3,1,2,3,1,2,3,1,2,2,3,1,2,3,1,2,3,1,3,
: 1,2,3,1,2,3,1,2,2,3,1,2,3,1,2,3,1),9,9)
: 
: jj3 <- structure(c(1,2,3,2,3,1,3,1,2,1,2,1,2,3,2,3,1,
: 3,1,3,1,2,1,2,3,2,3,2,3,1,3,1,2,1,2,3,2,3,
: 2,3,1,3,1,2,1,2,1,2,3,2,3,1,3,1,3,1,2,1,2,
: 3,2,3,1,3,1,3,1,2,1,2,3,2,3,2,3,1,3,1,2,1, 2),.Dim =
: as.integer(c(9,9)))
: 
: [ note that jj1-jj3 each have precisely 3 occurrences of A, B, and C
: along each row, column and (broken) diagonal ].
: 
: Can anyone give me a nice elegant way of creating jj2 and jj3 please?
:




More information about the R-help mailing list