xiaodai
xiaodai

Reputation: 16064

What's Julia's equivalent of R's seq(..., length.out = n)

I can see from this link that R's equivalent of seq is n:m in (http://www.johnmyleswhite.com/notebook/2012/04/09/comparing-julia-and-rs-vocabularies/).

But the case of seq(a,b, length.out = n) is not covered.

For example seq(1, 6, length.out=3) gives c(1.0, 3.5, 6.0). It is a really nice way to specify the number of outputs.

What's its equivalent in Julia?

Upvotes: 8

Views: 1527

Answers (2)

Cliff AB
Cliff AB

Reputation: 1190

As of Julia 1.0:

linspace has been deprecated. You can still use range:

julia> range(0, stop = 5, length = 3)
0.0:2.5:5.0

As @TasosPapastylianou noted, if you want this to be a vector of values, you can use collect:

julia> collect( range(0, stop = 5, length = 3) )
3-element Array{Float64,1}:
0.0
2.5
5.0

Upvotes: 6

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22255

You are looking for the linspace function. Note this is synonymous to the equivalent function in matlab / octave.

Also note that this returns a "steprange" type object:

julia> a = linspace(1,5,9)
1.0:0.5:5.0

julia> typeof(a)
StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}

julia> collect(a)
9-element Array{Float64,1}:
 1.0
 1.5
 2.0
 2.5
 3.0
 3.5
 4.0
 4.5
 5.0

PS: similarly, there exists a range function which is equivalent to the start:step:stop syntax, similar to the seq(from=, to=, by=) syntax in R.

Upvotes: 2

Related Questions