Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

vector
julia
communitycreator

How to create and use Vector in Julia

Programming Bytes

Overview

Vector in Julia is a one-dimensional array and mostly supports the same interface as their multi-dimensional counterparts.

Vector stores the elements in insertion order and can hold duplicate values.

Operations

Basic operations in Vector are:

  • push: It adds an element at the end of the Vector.
  • pushfirst: It adds an element at the start of the Vector.
  • pop: It removes the last element of the Vector.
  • popfirst: It removes the first element of the Vector.

We can create Vector in two ways by using:

  1. The Vector pre-defined keyword: vector_name = Vector{Datatype}([value1, value2, value3,…])
  2. The Vector elements within square brackets ([]): vector_name = [value1, value2, value3,…]

Code example

Let's look at the code below:


# with vector keyword
vector = Vector{Int}(1,2,3);

# vector with square bracketts
vector = [1,2,3]
Creating vector object

    Below is a sample code for using a Vector in Julia:

    using DataStructures
    
    # Create a vector 
    vector = Vector{Int}()
    
    # add elements to vector
    push!(vector, 2)
    push!(vector, 3)
    
    println("The vector is $(vector)")
    
    # add 1 to the beginning of the vector
    pushfirst!(vector, 1)
    println("\nAfter adding 1 as a first element, The vector is $(vector)")
    
    # remove last of the vector
    pop!(vector)
    println("\nAfter removing last element, The vector is $(vector)")
    
    # remove last of the vector
    popfirst!(vector)
    println("\nAfter removing first element, The vector is $(vector)")
    
    
    # emptying the vector 
    empty!(vector)
    
    println("After Emptying vector : $(vector)")
    Using vector

    Explanation

    • Line 4: We create a Vector object with the name vector which can have integer elements.
    • Lines 7 to 8: We use the push!() method to insert two elements into the vector.
    • Line 13: We use the pushfirst!() method to add an element to the start of the of the vector.
    • Line 17: We use the pop!() method to remove the last element of the vector.
    • Line 21: We use the popfirst!() method to remove the first element of the vector.
    • Line 26: We use the empty() method to remove all elements of the vector.

    RELATED TAGS

    vector
    julia
    communitycreator
    RELATED COURSES

    View all Courses

    Keep Exploring