# Create an object in the first iteration, then add to it

**URL:** https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348
**Category:** New to Julia
**Tags:** arrays
**Created:** [January 10, 2022, 6:45pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348 "2022-01-10T18:45:46Z")
**Posts on this page:** 16
**Page:** 1

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [January 10, 2022, 6:45pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/1 "2022-01-10T18:45:46Z")

</div>

I’m struggling with what seems like a simple coding pattern, but I seem unable to come up with a clean solution to it. Specifically, I often find myself needing to a) create a new object (such as a matrix) and then add to it inside an iteration.

What I’d _like_ to do is something like the following:

```
a = Array{Float64}
while (don't exit)
    append!(a, <stuff>)
end

```

where the first line would create an empty object and append() would add values to it, even if it’s initially empty.

But of course that doesn’t work – the call to append!() barfs. What I have to do instead is something like

```
a = nothing
while (don't exit)
    if a == nothing
        a = Array{Float64}(<initial stuff>)
    else
        append!(a, <new stuff>)
    end
end

```

…which, obviously, feels really clunky.

Yes, I _could_ - in some cases - pre-allocate an uninitialized array of the right size, but that isn’t always possible or desirable. For instance, Flux/Zygote doesn’t let you modify an array in place, because it screws with automatic differentiation. In some cases you don’t know how big the object is going to be before you start the iteration.

I’m currently having this same issue with generating a plot. I want to just create an empty plot and then add different data lines to it. But I can’t figure out how to generate a blank plot.

Am I being dumb here?

---

<div class="post-metadata">

### Author: ![rveltz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rveltz/32/2707_2.png) [@rveltz](https://discourse.julialang.org/u/rveltz)
#### Post date: [January 10, 2022, 6:58pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/2 "2022-01-10T18:58:47Z")

</div>

`a = Array{Float64}(undef, 0)` is empty array. You can push to it.

---

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [January 10, 2022, 7:17pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/3 "2022-01-10T19:17:17Z")

</div>

That’s neat, thanks. But it doesn’t seem to work in more complicated cases:

```
> a = Array{Float64}(undef, 0, 0)
> append!(a, [1, 2])
ERROR: MethodError: no method matching append!(::Matrix{Float64}, ::Matrix{Float64})
Closest candidates are:
  append!(::StructArrays.StructVector, ::Any) at ~/.julia/packages/StructArrays/MdA9B/src/tables.jl:24
  append!(::DataStructures.MutableLinkedList, ::Any...) at ~/.julia/packages/DataStructures/vSp4s/src/mutable_list.jl:160
  append!(::BitVector, ::Any) at ~/julia-1.7.1/share/julia/base/bitarray.jl:782

> cat(a, [5 6], dim=1)
ERROR: DimensionMismatch("mismatch in dimension 2 (expected 0 got 2)")

> a = [1 2; 3 4]
> cat(a, [5 6], dim=1)
3x2 Matrix{Int64}:
 1 2
 3 4
 5 6

```

---

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [January 10, 2022, 7:56pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/4 "2022-01-10T19:56:01Z")

</div>

> [@GlenHenshaw](#):
>
> That’s neat, thanks. But it doesn’t seem to work in more complicated cases:

Only 1d arrays can be dynamically resized in Julia. However, you can build resizable multi-dimensional arrays on top of this. For example, see [GitHub - JuliaArrays/ElasticArrays.jl: Resizeable multi-dimensional arrays for Julia](https://github.com/JuliaArrays/ElasticArrays.jl)

---

<div class="post-metadata">

### Author: ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)
#### Post date: [January 10, 2022, 8:08pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/5 "2022-01-10T20:08:48Z")

</div>

> [@GlenHenshaw](#):
>
> ```julia
> > a = Array{Float64}(undef, 0, 0)
> > append!(a, [1, 2])
> ERROR: MethodError: no method matching append!
> 
> ```

Maybe this:

```julia
a = Array{Float64}[]
append!(a, ([1, 2],)) # 1-element Vector{Array{Float64}}: [1.0, 2.0]
append!(a, ([4, 5],[6, 7]))

# can transform into other shapes needed, for example:
m = reduce(hcat, a)'

```

---

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [January 10, 2022, 8:47pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/6 "2022-01-10T20:47:00Z")

</div>

Without knowing what you are actually trying to accomplish, it’s

> [@GlenHenshaw](#):
>
> What I’d _like_ to do is something like the following:

The basic question here is why are you dynamically appending rows to a multidimensional array (if that is indeed what you want)? What are you actually trying to accomplish? Without knowing that, it’s hard to say whether you should be using an array-of-arrays approach, ElasticArrays or similar, an array of `SVector`, or …

---

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [January 10, 2022, 9:01pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/7 "2022-01-10T21:01:47Z")

</div>

In this particular case reading data from a file. The data consists of entries, each of which is a matrix. I’d like to accumulate all of it into a three-dimensional array.

In principle, I don’t really know how big each entry is; all I know is that all the entries are of the same size. I also don’t know how many of them there are. Figuring out the size of an entry is as simple as reading the first one. Figuring out how many of them there are would require traversing the entire file.

But this is a pain point that I seem to encounter often. In another part of this codebase I’m assembling a grid of plots which will show the data. I don’t know how many plots before runtime. I’d like to create an empty plot grid, probably with a known number of columns but an unknown number of rows, and keep appending plots to the end until I’m done.

---

<div class="post-metadata">

### Author: ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)
#### Post date: [January 10, 2022, 9:28pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/8 "2022-01-10T21:28:51Z")

</div>

Seems to me you’re looking for

```julia
a = Matrix{Float64}[]
while (don't exit)
    append!(a, <stuff>)
end

```

to collect your matrices and e.g.

```julia
cat(a..., dims = 3)

```

to turn them into a 3D array, or some more efficient alternative. Also depending on what `<stuff>` is, `push!` may be preferable to `append!`.

---

<div class="post-metadata">

### Author: ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)
#### Post date: [January 10, 2022, 9:29pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/9 "2022-01-10T21:29:28Z")

</div>

> [@GlenHenshaw](#):
>
> The data consists of entries, each of which is a matrix. I’d like to accumulate all of it into a three-dimensional array.

Couldn’t you accumulate the matrices like this (or `push!()` one by one):

```julia
a = Matrix{Float64}[]
append!(a, ([1 2; 2 1],))
append!(a, ([4 5; 6 7], [-1 0; 0 1]))

# transform into a three-dimensional array:
using TensorCast
@cast m[i,j,k] := a[i][j,k]

```

---

<div class="post-metadata">

### Author: ![nilshg](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nilshg/32/2283_2.png) [@nilshg](https://discourse.julialang.org/u/nilshg)
#### Post date: [January 10, 2022, 9:32pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/10 "2022-01-10T21:32:42Z")

</div>

The answer for plotting will depend on the plotting package, but for Plots.jl you can just put all plots in a vector and do `plot(vector_of_plots...)`

---

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [January 10, 2022, 10:01pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/11 "2022-01-10T22:01:54Z")

</div>

```
> using Plots
> using UnicodePlots
> unicodeplots()
> plt1 = lineplot(Plots.fakedata(10), Plots.fakedata(10));
> plt2 = lineplot(Plots.fakedata(10), Plots.fakedata(10));
> plot([plt1 plt2])

ERROR: Cannot convert Matrix{Plot{BrailleCanvas}} to series data for plotting
Stacktrace:
  [1] error(s::String)
@ Base ./error.jl:33
  [2] _prepare_series_data(x::Matrix{Plot{BrailleCanvas}})
@ RecipesPipeline ~/.julia/packages/RecipesPipeline/Bxu2O/src/series.jl:8
  [3] _series_data_vector(x::Matrix{Plot{BrailleCanvas}}, plotattributes::Dict{Symbol, Any})
@ RecipesPipeline ~/.julia/packages/RecipesPipeline/Bxu2O/src/series.jl:27
  [4] macro expansion
@ ~/.julia/packages/RecipesPipeline/Bxu2O/src/series.jl:144 [inlined]
  [5] apply_recipe(plotattributes::AbstractDict{Symbol, Any}, #unused#::Type{RecipesPipeline.SliceIt}, x::Any, y::Any, z::Any)
@ RecipesPipeline ~/.julia/packages/RecipesBase/qpxEX/src/RecipesBase.jl:289
  [6] _process_userrecipes!(plt::Any, plotattributes::Any, args::Any)
@ RecipesPipeline ~/.julia/packages/RecipesPipeline/Bxu2O/src/user_recipe.jl:36
  [7] recipe_pipeline!(plt::Any, plotattributes::Any, args::Any)
@ RecipesPipeline ~/.julia/packages/RecipesPipeline/Bxu2O/src/RecipesPipeline.jl:70
  [8] _plot!(plt::Plots.Plot, plotattributes::Any, args::Any)
@ Plots ~/.julia/packages/Plots/FI0vT/src/plot.jl:208
  [9] plot(args::Any; kw::Base.Pairs{Symbol, V, Tuple{Vararg{Symbol, N}}, NamedTuple{names, T}} where {V, N, names, T<:Tuple{Vararg{Any, N}}})
@ Plots ~/.julia/packages/Plots/FI0vT/src/plot.jl:91
  [10] plot(args::Any)
@ Plots ~/.julia/packages/Plots/FI0vT/src/plot.jl:85
  [11] top-level scope
@ REPL[58]:1
  [12] top-level scope
@ ~/.julia/packages/CUDA/sCev8/src/initialization.jl:52

```

---

<div class="post-metadata">

### Author: ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)
#### Post date: [January 10, 2022, 10:22pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/12 "2022-01-10T22:22:37Z")

</div>

> [@GlenHenshaw](#):
>
> ```julia
> > using Plots
> > using UnicodePlots
> > unicodeplots()
> > plt1 = lineplot(Plots.fakedata(10), Plots.fakedata(10));
> > plt2 = lineplot(Plots.fakedata(10), Plots.fakedata(10));
> > plot([plt1 plt2])
> 
> ERROR: Cannot convert Matrix{Plot{BrailleCanvas}} to series data for plotting
> Stacktrace:
> 
> ```

```julia
using Plots; unicodeplots()
plt1 = plot(Plots.fakedata(5), Plots.fakedata(5));
plt2 = plot(Plots.fakedata(5), Plots.fakedata(5));
plot(plt1, plt2)

```

or: `plot([plt1, plt2]...)`

---

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [January 10, 2022, 11:12pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/13 "2022-01-10T23:12:06Z")

</div>

Yes, it works if you call `plt1 = plot(...)`. But if you call `plt1 = lineplot(...)` it doesn’t.

---

<div class="post-metadata">

### Author: ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)
#### Post date: [January 10, 2022, 11:59pm UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/14 "2022-01-10T23:59:13Z")

</div>

Why should it work when calling `lineplot()`? It seems that there are no examples in the manual for subplotting using the results from this command.  
All examples use `plot()` or `scatter()` for that purpose.

---

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [January 11, 2022, 12:29am UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/15 "2022-01-11T00:29:07Z")

</div>

I guess I would ask the opposite. Every plot is a canvas, as far as I know. Why would it work for some types of plots and not others?

It turns out that this does work:

```
x1 = Plots.fakedata(10)
y1 = Plots.fakedata(10)
x2 = Plots.fakedata(10)
y2 = Plots.fakedata(10)
lineplot([x1 x2], [y2 y2], layout=2)

```

---

<div class="post-metadata">

### Author: ![nilshg](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nilshg/32/2283_2.png) [@nilshg](https://discourse.julialang.org/u/nilshg)
#### Post date: [January 11, 2022, 8:49am UTC](https://discourse.julialang.org/t/create-an-object-in-the-first-iteration-then-add-to-it/74348/16 "2022-01-11T08:49:51Z")

</div>

What is `lineplot`?

```julia
julia> using Plots

help?> lineplot
search:

Couldn't find lineplot
Perhaps you meant plot
  No documentation found.

  Binding lineplot does not exist.

```

It appears this is a function from `UnicodePlots`, not from `Plots`. You seem to misunderstand how `Plots` and its backends work - you just do `using Plots` and then choose your backend by calling the respective function as you have done above with `unicodeplots()`. You do **not** then do `using UnicodePlots` and mix functions defined in the backend plotting package with those defined in `Plots`.

Plotting multiple plots onto one figure is documented [here](https://docs.juliaplots.org/latest/tutorial/#Combining-Multiple-Plots-as-Subplots) (granted it does not include an example of using the splatting operator but then one could argue that’s just a basic language feature that Plots.jl doesn’t have to document separately).
