[R] analog to the matlab buffer function?

Marc Schwartz marc_schwartz at comcast.net
Fri Dec 1 02:56:58 CET 2006


Here is another possibility, though I may be missing how the Matlab
function handles incomplete rows generated at the end of the source
vector. I have not fully tested this, so it may yet require some
tweaking and certainly appropriate error checking.

I am presuming that the basic premise is that each row is of length
'window' and that it overlaps with the END of prior row by 'overlap'. 


Buffer <- function(x, window, overlap)
{
  Res <- NULL

  while (length(x) >= window)
  {
    Res <- c(Res, x[1:window])
    x <- x[(1 + window - overlap):length(x)]
  }

  matrix(Res, ncol = window, byrow = TRUE)
}


> Buffer(1:5, 3, 2)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    3    4
[3,]    3    4    5

> Buffer(1:10, 4, 2)
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    3    4    5    6
[3,]    5    6    7    8
[4,]    7    8    9   10

HTH,

Marc Schwartz


On Thu, 2006-11-30 at 16:32 -0800, Charles C. Berry wrote: 
> See
> 
>  	?embed
> 
> It is not quite the same, but this seems to be what you want - at least 
> for the example you give:
> 
> > t( embed(1:5,3) )[3:1,]
>       [,1] [,2] [,3]
> [1,]    1    2    3
> [2,]    2    3    4
> [3,]    3    4    5
> >
> 
> On Fri, 1 Dec 2006, Martin Ivanov wrote:
> 
> > Hello! I am new to R. I could not find a function analogous to matlab's 
> > function buffer, which is used in signal processing. Is there such a 
> > function in R? What I need to do is as follows. If I apply the function 
> > to the vector c(1:5) for example with a window length 3 and overlapping 
> > 2, I need to get a matrix like this:
> > 1 2 3
> > 2 3 4
> > 3 4 5
> > In matlab this is achieved with the function buffer. Is there ananalogous R function?




More information about the R-help mailing list