Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: short syntax for creating (1,n) array

Tags:

julia

In Matlab I can write:

[0:n]

to get an array (1,n). For n=2, I get:

  0     1     2  

How to do the same in Julia? The purpose is to get the same type of array (1,3).

I know I can write [0 1 2], but I want something general like in Matlab.

like image 319
pp11 Avatar asked Jul 27 '26 22:07

pp11


1 Answers

In julia, the colon operator (in this context, anyway) returns a UnitRange object. This is an iterable object; that means you can use it with a for loop, or you can collect all its contents, etc. If you collect its contents, what you get here is a Vector.

If what you're after is explicitly a RowVector, then you can collect the contents of the UnitRange, and reshape the resulting vector accordingly (which in this case can be done via a simple transpose operation).

julia> collect(1:3).'
1×3 RowVector{Int64,Array{Int64,1}}:
 1  2  3

The .' transpose operator is also defined for UnitRange arguments:

julia> (1:3).'
1×3 RowVector{Int64,UnitRange{Int64}}:
 1  2  3

However, note the difference in the resulting type; if you apply .' again, you get a UnitRange object back again.

If you don't particularly like having a "RowVector" object, and want a straightforward array, use that in an Array constructor:

julia> Array((1:3).')
1×3 Array{Int64,2}:
 1  2  3

(above as of latest julia 0.7 dev version)

like image 114
Tasos Papastylianou Avatar answered Jul 30 '26 10:07

Tasos Papastylianou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!