# Using views to mutate parts of arrays

**URL:** <https://discourse.julialang.org/t/using-views-to-mutate-parts-of-arrays/21306>\
**Category:** New to Julia\
**Created:** [February 28, 2019, 2:48pm UTC](https://discourse.julialang.org/t/using-views-to-mutate-parts-of-arrays/21306 "2019-02-28T14:48:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![HenrikM](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrikm/32/17975_2.png) [@HenrikM](https://discourse.julialang.org/u/HenrikM)\
**Post date:** [February 28, 2019, 2:48pm UTC](https://discourse.julialang.org/t/using-views-to-mutate-parts-of-arrays/21306/1 "2019-02-28T14:48:04Z")

</div>

I’m playing around with Julia 1.0.3 and getting confused. I have written a function that mutates an array. I want to use this function to mutate a part of a larger array. I can’t wrap my head around why some things work and some don’t. Here are examples:

```julia
function f!(x)
    for i in eachindex(x)
        x[i] = i
    end
end

x = randn(2, 3)
f!(view(x, :, :))
x

```

These work:

```julia
f!(view(x, :, :))
f!(view(x, 1, :))
f!(view(x, :, axes(x, 2)))
f!(view(x, 1, 1:2))

```

But these does not work:

```julia
f!(view(x, 1:2, 1:2))
f!(view(x, 1, 1))
f!(view(x, 1:2, 1:3))
f!(view(x, axes(x, 1), axes(x, 2)))
f!(view(x, axes(x, 1), :))

```

I don’t spot the pattern. Please help me understand.

---

<div class="post-metadata">

**Author:** ![yha](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yha/32/3502_2.png) [@yha](https://discourse.julialang.org/u/yha)\
**Post date:** [February 28, 2019, 3:07pm UTC](https://discourse.julialang.org/t/using-views-to-mutate-parts-of-arrays/21306/2 "2019-02-28T15:07:27Z")

</div>

The problem is that `eachindex` may return a `CartesianIndex` that can’t be stored back into an array of floats

```julia
> x = randn(2, 3)
> eachindex(view(x,1:2,1:2))
2×2 CartesianIndices{2,Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}}:
 CartesianIndex(1, 1) CartesianIndex(1, 2)
 CartesianIndex(2, 1) CartesianIndex(2, 2)

```

If `x` is an array of `Any`, your mutating function works as is

```julia
> x = Array{Any}(undef,2,3)
> f!(view(x,1:2,1:2))
> x
2×3 Array{Any,2}:
 CartesianIndex(1, 1) CartesianIndex(1, 2) #undef
 CartesianIndex(2, 1) CartesianIndex(2, 2) #undef

```

You can explicitly ask for linear (integer) indexes using `eachindex(IndexLinear(),x)` (these would probably be a bit less efficient for arbitrary views, since the iteration logic is more complicated).

---

<div class="post-metadata">

**Author:** ![HenrikM](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrikm/32/17975_2.png) [@HenrikM](https://discourse.julialang.org/u/HenrikM)\
**Post date:** [March 1, 2019, 10:41am UTC](https://discourse.julialang.org/t/using-views-to-mutate-parts-of-arrays/21306/3 "2019-03-01T10:41:46Z")

</div>

Of course, how silly of me.  
Thank you!
