# Mutating arrays not supported

**URL:** <https://discourse.julialang.org/t/mutating-arrays-not-supported/42123>\
**Category:** New to Julia\
**Tags:** flux, zygote, forwarddiff, tullio\
**Created:** [June 26, 2020, 7:50pm UTC](https://discourse.julialang.org/t/mutating-arrays-not-supported/42123 "2020-06-26T19:50:35Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![jmurray](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jmurray/32/15806_2.png) [@jmurray](https://discourse.julialang.org/u/jmurray)\
**Post date:** [June 27, 2020, 1:35am UTC](https://discourse.julialang.org/t/mutating-arrays-not-supported/42123/3 "2020-06-27T01:35:27Z")

</div>

@mcabbot, thank you for your feedback and the example.

After more reading, I think I understand the [distinction](https://discourse.julialang.org/t/assignment-and-mutation/19119) between an assignment (where a variable points to) and a mutation (changing its values). A mutation will not change the `objectid` but an assignment will.

Yet, inside the custom layer, I can create new arrays in memory – with or without assignment: for example, these are all allowed:

- `deepcopy(x_out)`
- `x_copy = deepcopy(x_out)`
- `sin.(x_copy)`
- `x_2 = sin.(x_copy)`

The `sin.(x_copy)` in particular is okay (apparently) because it creates a new array but does not change one. Likewise, your example using `vcat` works (apparently) because it’s building an array, not changing one.

To generalize your `vcat` example for an arbitrary number of rows, I see on the REPL that the following works:

```julia
x_out_mod = vcat([x_out[i:i,:] for i in 1:size(x_out, 1)]...) 

```

To apply elements of an array `f` of functions to each row, we’d just do

```julia
x_out_mod = vcat([f[i].(x_out[i:i,:]) for i in 1:size(x_out, 1)]...) 

```

But even the first line doesn’t work inside the custom layer: I get a `MethodError: no method matching iterate(::Nothing)` which I can’t make heads or tails of. Replacing `1:size(x_out, 1)` with `1:3` doesn’t help. Any ideas?

More conceptually, why aren’t mutations allowed? I thought I’d read that it has something to do with Flux not being able take gradients otherwise, but I don’t understand why it has no problem taking a gradient of a function broadcast to all elements and it would have a problem taking gradients of functions applied row-wise (which is my goal). Or why it’s okay to make new array but not to change an existing array (even one that is newly created and not tied to the `struct`).

---

_[View the full topic](https://discourse.julialang.org/t/mutating-arrays-not-supported/42123)._
