How to stores arrays in matrices

Hey guys,

I have a question regarding arrays and matrices:

I would like to create a 2D matrix where the first column contains arrays and the second column contains integer values, e.g.

Column 1 ----- Column 2
[“a” “b” “c”] -------- 1
[“d” “e” “f”] -------- 2
[“g” “h”] ------------ 4
[“i” “j” “k” “lm”] ---- 9

Unfortunately, when I try do this my array elements are “unpacked” and instead of storing the array as a whole, the individual elements are stored in the matrix.

For example:

a = [["a" "b" "c"] 2]


1×4 Array{Any,2}:
 "a"  "b"  "c"  2

instead of

1×2 Array{Any,2}:
 ["a" "b" "c"]  2

Now, I have found a workaround for this by saying

a = Any[0 2]
a[1] = ["a" "b" "c"]

But surely that cannot be the correct/clean way of doing that. So, how do I do this correctly?

PS: This is my first question ever, if I posted in the wrong category or something else please tell me how do it correctly. Thanks.

This is a bit of an unusual matrix, so I cannot find a nice way of constructing it with literals (not sure if it’s possible or not), but I would do this, which is pretty readable:

str = [["a", "b", "c"],
       ["d", "e", "f"],
       ["g", "h"],
       ["i", "j", "k", "lm"]]

num = [1, 2, 4, 9]

a = [str num]

As I said, this is a slightly odd matrix, are you sure that a matrix is the right data structure for what you are doing? Julia has a lot of nice data structures. If you are used to only using arrays, then it’s easy to overlook them.

Edit: Here’s a one-liner:

a = [[["a", "b", "c"], ["d", "e", "f"], ["g", "h"], ["i", "j", "k", "lm"]] [1, 2, 4, 9]]

Less readable, imho.


Thank you very much!

So, I guess the solution simply is to put double brackets around my array, i.e. [[“a” “b” “c”]].

Because this:
a = [[["a" "b" "c"]] 3]
then works exactly as I want it to, giving me:

1×2 Array{Any,2}:
 ["a" "b" "c"]  3

But to be honest, I still dont really understand why that is necessary… It seems overcomplicated or even wrong. I mean intuitively I would think that [[“x”]] gives me “x” in an array in an array…

The meaning of [x y] is concatenate x and y horizontally. You can see it like this

julia> [[1 2 3] [4 5]]
1×5 Array{Int64,2}:
 1  2  3  4  5

and it works similarly with a scalar:

julia> [[1 2 3] 4]
1×4 Array{Int64,2}:
 1  2  3  4

Then it logically follows that to do what you want you have to write

julia> [[[1 2 3]] 4]
1×2 Array{Any,2}:
 [1 2 3]  4

because concatenation will unpack the arrays to ‘fuse’ them together, so you have to pack it one extra layer deep.

Maybe what you are trying to do is ‘wrong’? :wink: I mean, are you sure you are using the right data structure for this?


To add to @DNF's remark, if you tell us what you want to do, you may get a better suggestion for the data structure to use. Usually, instead of packing everything into an array, a struct with names is a better alternative.