# Initializing lots of matrices in the same way

**URL:** https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500
**Category:** General Usage
**Created:** [June 18, 2023, 3:05am UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500 "2023-06-18T03:05:10Z")
**Posts on this page:** 20
**Page:** 1

<div class="post-metadata">

### Author: ![hshackle](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hshackle/32/47114_2.png) [@hshackle](https://discourse.julialang.org/u/hshackle)
#### Post date: [June 18, 2023, 3:05am UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/1 "2023-06-18T03:05:10Z")

</div>

The code I’m working with involves a few dozen matrices, let’s call them `a`, `b`, etc. They all end up being used in quite different fashions, so it makes sense to keep them separate rather than packing them all into one large array. However, they are all matrices of the same size and are all initialized in the same way. Is there any cleaner way to do this than just a long list of initializations:

```julia
a = zeros(Float64, 10, 10)
b = zeros(Float64, 10, 10)
...
y = zeros(Float64, 10, 10)
z = zeros(Float64, 10, 10)

```

---

<div class="post-metadata">

### Author: ![Alec\_Loudenback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/alec_loudenback/32/278_2.png) [@Alec\_Loudenback](https://discourse.julialang.org/u/Alec_Loudenback)
#### Post date: [June 18, 2023, 3:19am UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/2 "2023-06-18T03:19:00Z")

</div>

> [@hshackle](#):
>
> `zeros(Float64, 10, 10)`

`m = [zeros( 10, 10) for _ in 1:26]` and then you can refer to them by index. E.g. instead of `a` it would be `m[1]`, etc.

---

<div class="post-metadata">

### Author: ![hshackle](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hshackle/32/47114_2.png) [@hshackle](https://discourse.julialang.org/u/hshackle)
#### Post date: [June 18, 2023, 3:31am UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/3 "2023-06-18T03:31:59Z")

</div>

I would like to keep the arrays as separate variables; the actual names are more verbose and substantially increases readability. However, your solution should work if I just do `a, b, .... z = [zeros( 10, 10) for _ in 1:26] ` - thanks!

---

<div class="post-metadata">

### Author: ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)
#### Post date: [June 18, 2023, 6:31am UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/4 "2023-06-18T06:31:10Z")

</div>

> [@hshackle](#):
>
> a, b, … z = [zeros( 10, 10) for \_ in 1:26]

You could try using a generator instead of an array comprehension:

```julia
a, b, .... z = (zeros( 10, 10) for _ in 1:26) 

```

Then you avoid allocating the outer array.

Generators are lazy, so I think you could even make it infinitely long, and it will still only create the same number of matrices as the number of variables on the left hand side. In other words, you don’t need to count the variables, which I somehow find more satisfying.

---

<div class="post-metadata">

### Author: ![Boris](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/boris/32/3306_2.png) [@Boris](https://discourse.julialang.org/u/Boris)
#### Post date: [June 18, 2023, 8:21am UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/5 "2023-06-18T08:21:55Z")

</div>

Never new that existed, thanks!

---

<div class="post-metadata">

### Author: ![Dan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dan/32/42581_2.png) [@Dan](https://discourse.julialang.org/u/Dan)
#### Post date: [June 18, 2023, 3:16pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/6 "2023-06-18T15:16:14Z")

</div>

Another option is to use `NamedTuple`s. This keeps the readable names, but allows access through both names and indices and perhaps more importantly, passing and saving of the tuple of matrices. In code:

```julia
julia> names = (:a, :b, :c)
(:a, :b, :c)

julia> length(names)
3

julia> m = NamedTuple{names}(ntuple(i->zeros(3,3),length(names)))
(a = [0.0 0.0 0.0; 0.0 0.0 0.0; 0.0 0.0 0.0], b = [0.0 0.0 0.0; 0.0 0.0 0.0; 0.0 0.0 0.0], c = [0.0 0.0 0.0; 0.0 0.0 0.0; 0.0 0.0 0.0])

julia> m.a
3×3 Matrix{Float64}:
 0.0 0.0 0.0
 0.0 0.0 0.0
 0.0 0.0 0.0

julia> m[2]
3×3 Matrix{Float64}:
 0.0 0.0 0.0
 0.0 0.0 0.0
 0.0 0.0 0.0

```

If the matrices are of known sizes, then consider also using SArrays or MArrays which for smaller matrices provide more optimization (see StaticArrays package).

---

<div class="post-metadata">

### Author: ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)
#### Post date: [June 18, 2023, 4:21pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/7 "2023-06-18T16:21:17Z")

</div>

Your comment brings me back to this other (structurally similar, it seems to me) discussion.

[here](https://discourse.julialang.org/t/unpacking-a-named-tuple-using-field-names-and-slurping/100035/14)

I would think that the macros used to slurp part of a NamedTuple could be adapted to this situation, where rest=() and on the right hand side is a tuple with n repeating values.  
I’d be curious to see what this macro would look like?

---

<div class="post-metadata">

### Author: ![Dan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dan/32/42581_2.png) [@Dan](https://discourse.julialang.org/u/Dan)
#### Post date: [June 18, 2023, 4:58pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/8 "2023-06-18T16:58:53Z")

</div>

Speaking of Struct-utally similar questions. Would a `struct` be better than a `NamedTuple` in a general situation such as this? Is there a go-to package for conversions/initialization between NamedTuples and structs? As they seem similar to me in many ways.

---

<div class="post-metadata">

### Author: ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)
#### Post date: [June 18, 2023, 6:20pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/9 "2023-06-18T18:20:50Z")

</div>

I don’t know why the ntuple version didn’t work for me before, so I tried to do the NamedTuple one (\*)

```julia
macro assigNT(ex)
    vars = ex.args[1].args
    val = ex.args[2]
esc(quote
    $(vars...),= NamedTuple{Tuple($vars)}(ntuple(i->$val,length($vars)))
    end)
end

```

```julia
macro assignt(ex)
    vars = ex.args[1].args
    val = ex.args[2]
esc(quote
    $(vars...),= ntuple(i->$val,length($vars))
    end)
end

@assignt a,b,c,d = zeros(5,5)

julia> a
5×5 Matrix{Float64}:
 0.0 0.0 0.0 0.0 0.0
 0.0 0.0 0.0 0.0 0.0
 0.0 0.0 0.0 0.0 0.0
 0.0 0.0 0.0 0.0 0.0
 0.0 0.0 0.0 0.0 0.0

julia> c
5×5 Matrix{Float64}:
 0.0 0.0 0.0 0.0 0.0
 0.0 0.0 0.0 0.0 0.0
 0.0 0.0 0.0 0.0 0.0
 0.0 0.0 0.0 0.0 0.0
 0.0 0.0 0.0 0.0 0.0

```

(\*)

```julia
$(vars...),= ntuple(i->$val,length($vars))

```

maybe I overlooked the ‘,’ before the ='.  
Can anyone explain the difference with and without.  
I guess it’s something analogous to the fact that (1,) is a tuple of only the value 1, while (1) is only the value 1.  
But perhaps in the context of the expressions there is something else

---

<div class="post-metadata">

### Author: ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)
#### Post date: [June 18, 2023, 9:47pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/10 "2023-06-18T21:47:29Z")

</div>

I found this way to render in the form of a macro to the solution via generator, but I’m sure there is a simpler and faster way to achieve the same result via macro.

```julia
macro assigngen(ex)
    vars = ex.args[1].args
    val = ex.args[2]
    n=length(vars)
    itr = Expr(
            :(=),
            :_,
            esc(:(1:($n)))
        )
        
gen= Expr(
    :generator,
    esc(:($val)),
    itr
)
Expr(
    :(=),
    esc(:($(vars...),)),
    gen
)
end

```

---

<div class="post-metadata">

### Author: ![nsajko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nsajko/32/221187_2.png) [@nsajko](https://discourse.julialang.org/u/nsajko)
#### Post date: [June 18, 2023, 10:50pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/11 "2023-06-18T22:50:28Z")

</div>

Why are you using a macro instead of a function? Here’s a macroless solution:

```julia
f(::Val{names}, size::NTuple{n, Int}) where {names, n} =
  NamedTuple{names}(ntuple(
    let s = size
      _ -> zeros(s...)
    end,
    Val{length(names)}(),
  ))

```

In the REPL:

```julia-repl
julia> f(Val((:x, :y, :z)), (2, 3))
(x = [0.0 0.0 0.0; 0.0 0.0 0.0], y = [0.0 0.0 0.0; 0.0 0.0 0.0], z = [0.0 0.0 0.0; 0.0 0.0 0.0])

```

FYI, macros should be avoided whenever possible.

---

<div class="post-metadata">

### Author: ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)
#### Post date: [June 19, 2023, 9:49am UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/12 "2023-06-19T09:49:43Z")

</div>

Some solutions with functions had already been proposed and I wanted to try, for my exercise, to make some macros that after a lot of effort, I managed to get out.  
On the merits of the question, the expression that best responds to the OP’s request, in my opinion, is the one @DNF’s with the generator.  
As for macros, I’ve read that anything a macro does can be done by some function, so strictly speaking macros are never needed.  
But in some cases they can be convenient.

In this case, @DNF’s solution seems to be more functional and convenient than a macro.

---

<div class="post-metadata">

### Author: ![nsajko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nsajko/32/221187_2.png) [@nsajko](https://discourse.julialang.org/u/nsajko)
#### Post date: [June 19, 2023, 11:39am UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/13 "2023-06-19T11:39:59Z")

</div>

The solution with a generator seems like it could be more problematic, or at least less flexible.

The problem is that the length of the generator is a run-time value, while the number of your matrices is akin to the length of a `Tuple`, which is a compilation-time value. The mismatch might not matter in a lot of cases due to Julia’s smart type inference and constant propagation, however it seems like it could cause run time dispatch and slow things down in some cases if used carelessly.

---

<div class="post-metadata">

### Author: ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)
#### Post date: [June 19, 2023, 3:57pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/14 "2023-06-19T15:57:50Z")

</div>

> [@nsajko](#):
>
> the length of the generator is a run-time value

You can make the generator infinitely long, it doesn’t matter. It’s the lhs that determines the length.

---

<div class="post-metadata">

### Author: ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)
#### Post date: [June 19, 2023, 5:50pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/15 "2023-06-19T17:50:25Z")

</div>

For the fun of it (probably not the most elegant way of doing that):

```julia
julia> struct InfinitelyIterable end

julia> import Base:iterate

julia> Base.iterate(::InfinitelyIterable, state) = ((InfinitelyIterable(), 1), 1)

julia> a, b, c = (zeros(3,3) for _ in InfinitelyIterable());

julia> a
3×3 Matrix{Float64}:
 0.0 0.0 0.0
 0.0 0.0 0.0
 0.0 0.0 0.0

julia> b
3×3 Matrix{Float64}:
 0.0 0.0 0.0
 0.0 0.0 0.0
 0.0 0.0 0.0

julia> c
3×3 Matrix{Float64}:
 0.0 0.0 0.0
 0.0 0.0 0.0
 0.0 0.0 0.0

```

---

<div class="post-metadata">

### Author: ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)
#### Post date: [June 19, 2023, 6:54pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/16 "2023-06-19T18:54:03Z")

</div>

> [@lmiq](#):
>
> `a, b, c = (zeros(3,3) for _ in InfinitelyIterable());`

Indeed. You can also use

```julia
a, b, c = (zeros(3,3) for _ in Iterators.countfrom());

```

---

<div class="post-metadata">

### Author: ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)
#### Post date: [June 19, 2023, 7:04pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/17 "2023-06-19T19:04:45Z")

</div>

without the use of an intermediate generator

```julia
julia> A,B,C,D =Iterators.repeated(ones(2,3))
Base.Iterators.Repeated{Matrix{Float64}}([1.0 1.0 1.0; 1.0 1.0 1.0])

julia> A
2×3 Matrix{Float64}:
 1.0 1.0 1.0
 1.0 1.0 1.0

julia> D
2×3 Matrix{Float64}:
 1.0 1.0 1.0
 1.0 1.0 1.0

```

---

<div class="post-metadata">

### Author: ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)
#### Post date: [June 19, 2023, 8:02pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/18 "2023-06-19T20:02:32Z")

</div>

```julia

julia> A,B,C,D =Iterators.repeated(ones(2,3))
Base.Iterators.Repeated{Matrix{Float64}}([1.0 1.0 1.0; 1.0 1.0 1.0])

julia> A[1] = 9
9

julia> B
2×3 Matrix{Float64}:
 9.0 1.0 1.0
 1.0 1.0 1.0

```

---

<div class="post-metadata">

### Author: ![Dan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dan/32/42581_2.png) [@Dan](https://discourse.julialang.org/u/Dan)
#### Post date: [June 19, 2023, 9:04pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/19 "2023-06-19T21:04:08Z")

</div>

```julia
julia> import IterTools as Itr

julia> A,B,C,D = Itr.repeatedly(()->ones(2,3))

julia> A[1] = 9

julia> B
2×3 Matrix{Float64}:
 1.0 1.0 1.0
 1.0 1.0 1.0

```

---

<div class="post-metadata">

### Author: ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)
#### Post date: [June 19, 2023, 10:41pm UTC](https://discourse.julialang.org/t/initializing-lots-of-matrices-in-the-same-way/100500/20 "2023-06-19T22:41:31Z")

</div>

Another option is to use `@eval`:

```julia
vars = (:a, :b, :c)
for var in vars
    @eval $var = zeros(2, 2)
end

```
