# How do I incorporate a boundary function for a vector in another function

Y’all gonna see a lot from me cuz i dunno what the fuck i’m doing :). Working on problem set 2 of the MIT course and i’ve hit a wall. The question is:

Write a function `box_blur(v, l)` that blurs a vector `v` with a window of length `l` by averaging the elements within a window from `-l` to `l`. This is called a box blur. Use your function `extend` to handle the boundaries correctly.

Return a vector of the same size as `v`.

My extend function is:

``````function extend(v::AbstractVector, i)
n = length(v)

if i in 1:n
return v[i]
elseif i < 1
return v[1]
else
return v[n]
end
end
``````

my mean function is

``````function mean(v)
total = 0
n = length(v)
for s in 1:n
total += v[s]
end
end
``````

my initial just straight up non-programmer logic for the box blur was:

``````function box_blur(v::AbstractArray, l)
vn = copy(v)
n = length(v)
for i in vn
window = i-l:i+l
vn[i] = mean(extend(window, i))
end
return vn
end
``````

I still end up with “ArgumentError: invalid index: 1.0 of type Float64” so i know the code must be nonsense but I don’t know how to incorporate the extend function to ensure the proper boundary.

You are iterating over the vector elements of vn and in your loop you index with the entries of you vector. This doesn’t work as you cant index an array with floats.

Maybe you meant to loop over `1:n`?

``````function box_blur(v::AbstractArray, l)
vn = copy(v)
n = length(v)
for i in 1:n
window = i-l:i+l
vn[i] = mean(extend(window, i))
end
return vn
end
``````

Aaaaah yes I did mean to do that, I even prepared in the line before to do that. Well my code is still clearly nonsense and idk what it’s even doing lmao. This is what it’s doing:

example_vector = [0.8, 0.2, 0.1, 0.7, 0.6, 0.4]

After i input it into: box_blur(example_vector, 1), it turns into this

0.0, 3.0, 2.0, 3.0, 4.0, 5.0

computational logic makes my head hurt

I do probably do it something like this:

``````extend(v::AbstractVector{T}, n) where T = [fill(v[1],n); v; fill(v[end], n)]

function box_blur(v,l)
v_ex = extend(v,l)
v_blurred = [sum(v_ex[i:(i+2*l)])/(2l+1) for i in 1:length(v)]
end
``````

EDIT: I thought extend meant filling with 0, but apparently it is extending it with the same value.