# Convert buffer function existing in matlab to julia language

**URL:** <https://discourse.julialang.org/t/convert-buffer-function-existing-in-matlab-to-julia-language/98926>\
**Category:** General Usage\
**Tags:** question\
**Created:** [May 16, 2023, 11:43am UTC](https://discourse.julialang.org/t/convert-buffer-function-existing-in-matlab-to-julia-language/98926 "2023-05-16T11:43:02Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [May 17, 2023, 1:04pm UTC](https://discourse.julialang.org/t/convert-buffer-function-existing-in-matlab-to-julia-language/98926/6 "2023-05-17T13:04:51Z")

</div>

Sounds like you want something like:

```julia
@views buffer(X, n, p=0) = [X[i:i+n-1] for i in firstindex(X):n-p:lastindex(X)-n+1]

```

This returns an array of [views of `X`](https://docs.julialang.org/en/v1/base/arrays/#Views-(SubArrays-and-other-view-types)) rather than copies.

If you want to stack these “frames” into a matrix, similar to Matlab, you can do `stack(buffer(X, n, p))`, but I would eventually try to re-think your code to avoid making copies of all the data like this. (In general, Matlab contorts you into a particular “vectorized” style of programming because Matlab loops are slow, and there is often a faster and more natural way to do things in Julia once you get used to it.)

e.g.

```julia
julia> stack(buffer(1:11, 3, 1))
3×5 Matrix{Int64}:
 1 3 5 7 9
 2 4 6 8 10
 3 5 7 9 11

```

I’m not sure if this is exactly the desired output? I don’t have Matlab handy, but the [GNU Octave `buffer` function](https://sourceforge.net/p/octave/signal/ci/default/tree/inst/buffer.m) puts zeros at the beginning and end for some reason:

```plaintext
octave:1> buffer(1:11, 3, 1)
ans =

    0 2 4 6 8 10
    1 3 5 7 9 11
    2 4 6 8 10 0

```

You could easily tweak my implementation above to do this, e.g. by first zero-padding `X` (or, to avoid copies, by wrapping `X` in a zero-`PaddedView` from [PaddedViews.jl](https://github.com/JuliaArrays/PaddedViews.jl)). (The explicit-loop implementation by @GunnarFarneback in [another thread](https://discourse.julialang.org/t/converting-python-code-into-julia-code/98991/7) has the zero-padding built-in, but doesn’t return views.)

---

_[View the full topic](https://discourse.julialang.org/t/convert-buffer-function-existing-in-matlab-to-julia-language/98926)._
