In this shot, we will learn about arrays in Julia.
An array is an ordered collection of items.
In Julia, we can create arrays that hold multiple types of values, or we can restrict them to hold a single type of value.
There are two types of arrays in Julia:
We can declare a one-dimensional array either like this:
array_name = type_of_array[value1, value2, value3]
array_name = [value1, value2, value3]
where some examples of
Float64, and so on, and comma-separated values are provided between the square brackets
We can declare a two-dimensional array either like this:
array_name = type_of_array[value1, value2, value3 ; value4, value5, value6]
array_name = [value1, value2, value3 ; value4, value5, value6]
where values are separated by a space and every row is separated using a semicolon (
In the following example, we are creating a one-dimensional array,
integer_array, which is of type
Int64. This means that we are restricting it to store only values of type
Int64. In the example, we are also creating a string array named
string_array and storing string values in it.
#declare and initialize the single dimensional array integer_array = Int64[1000,2000, 3000, 4000] string_array = ["Adam", "Eve", "Sara"] print(integer_array) print("\n") print(string_array)
In the following example, we are creating a two-dimensional array of type
Int64, where each of the values are separated by a
space and all of the rows are separated by semicolons (
#declare and initialize the two dimensional array integer_array = Int64[1000 2000 3000 ; 4000 5000 6000] #use display to pretty print the 2d array display(integer_array)
In Julia, the index of arrays starts from
1, unlike in other languages where the index starts from
We can access any element by providing its index between square brackets.
We can access a two-dimensional array using its row and column indices.
Let’s look at an example of how we can access an element from an array in Julia:
#declare and initialize the single dimensional array integer_array_1d = Int64[1000, 2000, 3000, 4000] #access element at second postion println(integer_array_1d) #declare and initialize the two dimensional array integer_array_2d = Int64[1000 2000 3000 ; 4000 5000 6000] #access element at second row, first column println(integer_array_2d)
View all Courses