In this shot, we will learn about the range function in Julia.
The range() function is used to create a range of objects.
We’ll use the following syntax to create it:
range(start, stop, length)
or
range(start, stop, step)
The range()
function accepts below parameters:
start
: To provide the starting value in the range.stop
: To provide the ending value in the range.length
: To specify how many objects should create for a given range. It means it will take the start
and stop
, and then it will divide the difference between them equally. For example if start = 1,stop = 100 and length = 10, then we will have range as 1.0:11.0:100.0
Where 11.0
is difference between two subsequent objects in the range. For this example, we will have a range of objects as 1.0, 12.0, 23.0, ... 100.0
. As you can see, there is a difference of 11.0
between the two subsequent objects.step
: To specify how many objects to skip.Note: We can only choose one of the parameters between
length
andstep
.
Let’s take a look at an example to understand it better:
In the following example, we create two different range objects using both syntaxes provided above:
#range using lengthprintln(range(start = 1, length=10, stop=100))#range using stepprintln(range(start = 1, stop=200, step=10))
Line 2: We use a range function with length as 10
, then the range function creates 10
objects between given range 1 to 100
.
Line 5: We use a range function with a step as 10
, then the function creates objects with a gap of 10 for each object till given maximum range (stop
).
When we run the above code snippet, we get output as start
:difference between two subsequent objects
: stop
One of the use cases of this range function is to create an array of objects.
If we pass this range as a parameter to collect the function, it creates an array of objects.
Let’s look at the following code snippet to understand it better:
#range using lengthprintln(collect(range(start = 1, length=10, stop=150)))#range using stepprintln(collect(range(start = 1, stop=200, step=10)))
In the above code snippet, we pass the above ranges to different collect functions and print the result.
When we run the above code snippet, we get an output of two different arrays of objects created from given ranges.