How do you generate a regular non-integer sequence in julia?

They are generated the same way as in Matlab

julia> sequence = 0:.1:1
0.0:0.1:1.0

Alternatively, you can use the range() function, which allows you to specify the length, step size, or both

julia> range(0, 1, length = 5)
0.0:0.25:1.0

julia> range(0, 1, step = .01)
0.0:0.01:1.0

julia> range(0, step = .01, length = 5)
0.0:0.01:0.04

You can still do all of the thinks you would normally do with a vector, eg indexing

julia> sequence[4]
0.3

math and stats...

julia> sum(sequence)
5.5

julia> using Statistics

julia> mean(sequence)
0.5

This will (in most cases) work the same way as a vector, but nothing is actually allocated. It can be comfortable to make the vector, but in most cases you shouldn't (it's less performant). This works because

julia> sequence isa AbstractArray
true

If you truly need the vector, you can collect(), splat (...) or use a comprehension:

julia> v = collect(sequence)
11-element Array{Float64,1}:
 0.0
 0.1
 0.2
 0.3
 0.4
 0.5
 0.6
 0.7
 0.8
 0.9
 1.0

julia> v == [sequence...] == [x for x in sequence]
true

The original answer is now deprecated. You should use collect() to generate a sequence.

## In Julia
> collect(0:.1:1)
10-element Array{Float64,1}:
 0.1
 0.2
 0.3
 0.4
 0.5
 0.6
 0.7
 0.8
 0.9
 1.0

## In R
> seq(0, 1, .1)
 [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

Similarly to Matlab, but with the difference that 0.1:0.1:1 defines a Range:

julia> typeof(0.1:0.1:1)
Range{Float64} (constructor with 3 methods)

and thus if an Array is needed:

julia> [0.1:0.1:1]
10-element Array{Float64,1}:
 0.1
 0.2
 0.3
 0.4
 0.5
 0.6
 0.7
 0.8
 0.9
 1.0

Unfortunately, this use of Range is only briefly mentioned at this point of the documentation.

Edit: As mentioned in the comments by @ivarne it is possible to achieve a similar result using linspace:

julia> linspace(.1,1,10)
10-element Array{Float64,1}:
 0.1
 0.2
 0.3
 0.4
 0.5
 0.6
 0.7
 0.8
 0.9
 1.0

but note that the results are not exactly the same due to rounding differences:

julia> linspace(.1,1,10)==[0.1:0.1:1]
false

Tags:

Julia