What is a collect function in Julia?

In this shot, we will learn about the collect function in Julia.

The collect() function is used to create an array of objects.

We will use the following syntax for collect() function.

Syntax

There are two ways of using the following syntax:

collect(start,stop)
collect(start,step,stop)

Parameters

The collect() function accepts the following parameters:

  • start: This is used to specify the starting object of the range.
  • step: This is used to specify to skip the objects for which no steps are provided. It defaults to 1.
  • stop: This is used to specify the maximum for the range.

Returns

The collect() function returns an array of objects for the given range.

Let’s look at an example to better understand this:

Example without step value

In the following example, we create an array of objects for the range 1 to 10 and, since we are not providing any step value, it will take 1 as the default step.

The display function is used to display the array that is returned by the collect function.

#Using collect without step
display(collect(1:10))

Example with step value

In the following example, we are creating an array of objects for the range 1 to 10, using 2 as the step. Hence, the collect function will skip 2 objects for each object created in the array.

#Using collect with step
display(collect(1:2:10))

Free Resources