# Seven Lines of Julia (examples sought)

**URL:** <https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416>\
**Category:** General Usage\
**Created:** [November 19, 2020, 7:37am UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416 "2020-11-19T07:37:29Z")\
**Posts on this page:** 1\
**Showing post:** 48

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [December 8, 2020, 4:33pm UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/48 "2020-12-08T16:33:33Z")

</div>

Calculating a cross-correlation in any number of dimensions:

```julia
for I in CartesianIndices(img)
    for J in CartesianIndices(kernel) # kernel with centered indices
        if I+J in CartesianIndices(img)
            filtered[I] += img[I+J] * kernel[J]
        end
    end
end

```

(Inspired by [Multidimensional algorithms and iteration](https://julialang.org/blog/2016/02/iteration/) and [Knowing where you are: custom array indices in Julia](https://julialang.org/blog/2017/04/offset-arrays/.))

The code in action:

```julia
using OffsetArrays
using Makie

# A 3D "image" of random values (either 0 or 1)
img = rand([0.0, 1.0], 20, 60, 40)

# Plot
s1 = volume(img, algorithm=:iso, resolution=(800, 500))

# Function to generate an N-dimensional kernel of uniform values that sum to 1
# The center of the hypercube will have indices (0, 0, ..., 0)
uniform_kernel(n, dim) = OffsetArray(fill(1/n^dim, fill(n, dim)...), fill(-n÷2-1, dim)...)

# 5x5x5 array of uniform values that sum to 1
kernel = uniform_kernel(5, 3) # 3 dimensions

filtered = zero(img)

for I in CartesianIndices(img)
    for J in CartesianIndices(kernel)
        if I+J in CartesianIndices(img)
            filtered[I] += img[I+J] * kernel[J]
        end
    end
end

s2 = volume(filtered, algorithm=:iso, resolution=(800, 500))

```

Original image:  
 ![image](https://global.discourse-cdn.com/julialang/original/3X/c/8/c830b70312b79e26d6449467a67abb4591835633.jpeg)

Filtered image: ![filtered](https://global.discourse-cdn.com/julialang/original/3X/3/a/3afe5e8dda0c075b955fe7ae01d3e7df484ea71b.jpeg)

---

_[View the full topic](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416)._
