# [R] Matrix from a vector?

Petr Pikal petr.pikal at precheza.cz
Fri Sep 22 08:58:48 CEST 2006

```Hi

other approach is to use embed

embed(c(rhsel,rhsel),length(rhsel))[-1,]
which is a little bit quicker

rhsel<-rnorm(1000)
n <- length(rhsel)

system.time({
i <- sapply(1:n, function(i) (1:n - i)%%n + 1)
x2<-matrix(rhsel[i], n, n)
})

system.time(x1<-embed(c(rhsel,rhsel),length(rhsel))[-1,])

all.equal(x1,x2)

HTH
Petr

On 21 Sep 2006 at 14:53, Sundar Dorai-Raj wrote:

Date sent:      	Thu, 21 Sep 2006 14:53:52 -0500
From:           	Sundar Dorai-Raj <sundar.dorai-raj at pdf.com>
Organization:   	PDF Solutions, Inc.
To:             	kone <attenka at utu.fi>
Copies to:      	r-help at stat.math.ethz.ch
Subject:        	Re: [R] Matrix from a vector?

>
>
> kone said the following on 9/21/2006 2:30 PM:
> > Hi,
> >
> > Is there some function, which generates this kind of n x n -matrix
> > from a vector?
> >
> >  > rhset
> > [1]  1792   256 13312   512  1024  2048  8192  4096
> >  > 	m=matrix(nrow=length(rhset),ncol=length(rhset))
> >  > 	for(i in 1:length(rhset))
> > + 	{
> > + 		m[,i]=rhset
> > + 		rhset=c(rhset[length(rhset)], rhset[2:length(rhset)-1])
> > + 	}
> >  > m
> >        [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]
> > [1,]  1792  4096  8192  2048  1024   512 13312   256
> > [2,]   256  1792  4096  8192  2048  1024   512 13312
> > [3,] 13312   256  1792  4096  8192  2048  1024   512
> > [4,]   512 13312   256  1792  4096  8192  2048  1024
> > [5,]  1024   512 13312   256  1792  4096  8192  2048
> > [6,]  2048  1024   512 13312   256  1792  4096  8192
> > [7,]  8192  2048  1024   512 13312   256  1792  4096
> > [8,]  4096  8192  2048  1024   512 13312   256  1792
> >
> >
> > Atte Tenkanen
> > University of Turku, Finland
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > http://www.R-project.org/posting-guide.html and provide commented,
> > minimal, self-contained, reproducible code.
>
>
> Does this work for you?
>
> rhsel <- c(1792, 256, 13312, 512, 1024, 2048, 8192, 4096)
> n <- length(rhsel)
> i <- sapply(1:n, function(i) (1:n - i)%%n + 1)
> matrix(rhsel[i], n, n)
>
> HTH,
>
> --sundar
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help