David Zhang
David Zhang

Reputation: 4364

Declaring multiple arrays in Julia

Suppose I need to declare (but not initialize the values of) five 10x10 arrays, named, say, A1-A5. Fortran has a nice syntax for this kind of multiple array declaration:

REAL(8), DIMENSION(10,10) :: A1, A2, A3, A4, A5

However, the only method in Julia I am aware of is much uglier:

A1 = Array(Float64, 10, 10)
A2 = Array(Float64, 10, 10)
A3 = Array(Float64, 10, 10)
A4 = Array(Float64, 10, 10)
A5 = Array(Float64, 10, 10)

Is there any more concise way to declare multiple arrays of the same dimension in Julia?

Upvotes: 4

Views: 1106

Answers (2)

JKnight
JKnight

Reputation: 2006

Thanks to some help from @simonster in another question you can succinctly declare your variables without any runtime overhead using metaprogramming,

for x = [:A1,:A2,:A3,:A4,:A5]
    @eval $x = Array(Float64,10,10)
end

However, we can now do one step better than Fortran by allowing you to generate the names dynamically as well:

for x in [symbol("A"*string(i)) for i=1:100]
    @eval $x = Array(Float64,10,10)
end

This will allocate 100 arrays A1-A100. Thanks to @rickhf12hs's comment for this idea/implementation.

Upvotes: 10

Toivo Henningsson
Toivo Henningsson

Reputation: 2699

Assuming it's ok to create one temporary array holding the resulting five arrays, you could use an array comprehension:

A1, A2, A3, A4, A5 = [Array(Float64, 10, 10) for i = 1:5]

Upvotes: 1

Related Questions