Initialize an array (or other structure), add

I’m looking to create something like this:

array = [(0,0) (0,0) ;(0,0) (0,0) ; (0,0) (0,0)]

To store the results of a loop where the first iteration returns an array of pairs that I use to overwrite column 1

[(m,n); (m,n); (m,n)]

and the second iteration produces another array of pairs

[(m,n); (m,n); (m,n)]

that I use to overwrite col 2.

I’ve tried initializing using “zeros()”, but that does not work, and it seems like tuples are not initalize-able in Julia?

You can initialize it as:

julia> arr = Array{Tuple{Int, Int}}(undef, 3, 2)
3×2 Matrix{Tuple{Int64, Int64}}:
 (0, 0)  (0, 0)
 (0, 0)  (0, 0)
 (0, 0)  (0, 0)

The values aren’t guaranteed to be (0, 0) when using the undef initializer, but that should be fine here since you’re going to be replacing them anyway. If you do need them to be (0, 0), you can use fill instead.

julia> arr = fill((0, 0), 3, 2)
3×2 Matrix{Tuple{Int64, Int64}}:
 (0, 0)  (0, 0)
 (0, 0)  (0, 0)
 (0, 0)  (0, 0)
1 Like

Thank you!! And once I have a tuple, say, this: how would I index to the upper right hand corner (7,1)?

10×2 Matrix{Tuple{Int64, Int64}}:
 (5, 1)   (7, 1)
 (5, 2)   (7, 2)
 (5, 3)   (7, 3)
 (5, 4)   (7, 4)
 (5, 5)   (7, 5)
 (5, 6)   (7, 6)
 (5, 7)   (7, 7)
 (5, 8)   (7, 8)
 (5, 9)   (7, 9)
 (5, 10)  (7, 10)

Oh wait it’s like this: Lok[7,2][2]

If you want to get to the (7, 1) element of the matrix, you can do it as:

Lok[1, 2]

(Lok is the name of your matrix here.)

This is because (7, 1) is in row 1 and column 2 of the matrix.

                   Column 2
                     |
                     \/
Row 1 --> (5, 1)   (7, 1)
          (5, 2)   (7, 2)
          (5, 3)   (7, 3)
          (5, 4)   (7, 4)
          (5, 5)   (7, 5)
          (5, 6)   (7, 6)
          (5, 7)   (7, 7)
          (5, 8)   (7, 8)
          (5, 9)   (7, 9)
          (5, 10)  (7, 10)

Lok[7, 2] on the other hand gets you the element in the 7th row, 2nd column, which is (7, 7). So doing Lok[7, 2][2] gets you the second element within (7, 7), which would be a 7.

By the way, if these values from the loop are distinct results that don’t need to be together, it might be better to have them as just two separate matrices, rather than a matrix containing tuples like this. A lot depends on your specific scenario though, but it’s something to consider in case accessing the values the way you want turns out inconvenient with this setup.