Initialize Arrays from Ranges, Semicolon explanation

Hello,

I’ve just read that I can initialize arrays from a range using the following syntax:

my_array = [1:10;]

What is the semicolon doing in this expression?

I thought that the ; can be used to separate rows as follows:
my_array = [1; 2; 3; 4; 5]

The semicolon denotes vertical concatenation. Separating elements with commas will make a list of those elements, while separating elements with semicolons or spaces will concatenate them — vertically for semicolons, and horizontally for spaces.

1 Like

Yes, that makes sense. However, that is not my question. I was expecting this code to work:

my_array = [1:10]

but it makes a UnitRange instead of an Array{Int64}

so, again, what is the significance of the semicolon:

my_array = [1:10;]

Based on your answer, it should be vertically concatenating…but in this case of a range, what exactly is it vertically concatenating!?

You should read the docs, and this discussion:

That said, it is very likely that you want to use 1:10 as is (without allocating an array), or if you want to modify values, collect(1:10).

As @Tamas_Papp noted, you should probably use 1:10 as is or collect it. But just to answer this question: [1:10] is not a unit range, but rather a vector with the single element 1:10 (which is a UnitRange).
[1:10;] is the same as vcat(1:10). vcat returns the concatenated result as an Array, so in this case of a single argument, it simply converts it to an array (the fact that vcat return an Array does not seem to be documented, so I suppose it could just as well have returned its argument 1:10 unmodified).

1 Like

@yha Yea, I should have and meant to say an Array of 1-element UnitRange. I posted this question on StackOverflow and I got an interesting answer.

Also, my question wasn’t whether I can use collect to simplify things. I am not looking for an answer about how to create arrays from ranges, per se. I wanted to get to the bottom of the syntax. Sorry, I have not made it clear enough.

https://stackoverflow.com/questions/55438134/creating-arrays-from-ranges-in-julia-without-using-collect

I found the answer to be quite fascinating and staisfying. Especially, using the Debugger to get into the weeds of Vector() function.