# Using CartesianIndices with view()

**URL:** <https://discourse.julialang.org/t/using-cartesianindices-with-view/58411>\
**Category:** General Usage\
**Tags:** indexing\
**Created:** [April 2, 2021, 4:27am UTC](https://discourse.julialang.org/t/using-cartesianindices-with-view/58411 "2021-04-02T04:27:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Phil\_Tomson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/phil_tomson/32/3575_2.png) [@Phil\_Tomson](https://discourse.julialang.org/u/Phil_Tomson)\
**Post date:** [April 2, 2021, 4:27am UTC](https://discourse.julialang.org/t/using-cartesianindices-with-view/58411/1 "2021-04-02T04:27:16Z")

</div>

I’ve got this function for computing the next state of a CA:

```julia
 function convGOL_dot(A::AbstractMatrix, kern::AbstractMatrix)
 	b = CartesianIndex(1,1)
 	out = zeros(eltype(A), size(A))
 	@inbounds for i in CartesianIndices(A)[2:end-1, 2:end-1]
 		count = dot(A[i-b:i+b], kern)
 		out[i] = liveordie(count, A[i])
 	end
 	out
 end

```

Given the right 3x3 kernel this function does what I want it to - it functions correctly. However, those 2D array slices there (A[i-b:i+b]) result in a lot of unnecessary allocations. I’d like to replace that line where the dot product is being calculated with a view into A. Something along the lines of:

```julia
 function convGOL_dot(A::AbstractMatrix, kern::AbstractMatrix)
 	b = CartesianIndex(1,1)
 	out = zeros(eltype(A), size(A))
 	@inbounds for i in CartesianIndices(A)[2:end-1, 2:end-1]
 		count = dot(view(A, i-b, i+b), kern)
 		out[i] = liveordie(count, A[i])
 	end
 	out
 end

```

… though that’s not doing the correct thing (the view isn’t producing a 3x3 2d array which causes the dot function to fail with a dimension mismatch). Is there something I need to do differently to use CartesianIndex’es there? How would I go about this?

---

<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:** [April 2, 2021, 7:01am UTC](https://discourse.julialang.org/t/using-cartesianindices-with-view/58411/2 "2021-04-02T07:01:56Z")

</div>

I get `BoundsError: attempt to access 5×5 Matrix{Float64} at index [1, 1, 3, 3]` with the following test case:

```julia
A = zeros(5,5);
b = CartesianIndex(1,1);
i = first(CartesianIndices(A)[2:end-1, 2:end-1]);
view(A, i-b, i+b)

```

I think you want `view(A, i-b:i+b)`.

---

<div class="post-metadata">

**Author:** ![Phil\_Tomson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/phil_tomson/32/3575_2.png) [@Phil\_Tomson](https://discourse.julialang.org/u/Phil_Tomson)\
**Post date:** [April 2, 2021, 3:18pm UTC](https://discourse.julialang.org/t/using-cartesianindices-with-view/58411/3 "2021-04-02T15:18:11Z")

</div>

Thanks, that works. It seems I was over-complicating it.
