Post Contents

Summary: This is an ultimate tutorial guide on Julia programming which can help you to get started with the language.

Introduction to Julia Programming

Julia is a relatively new high performing programming language which came out in 2012. This is an open source language licenced under the MIT license.

We can use Julia as a general purpose programming language to build our day to day applications, but the language itself and many of its features are well suited for scientific computing, numerical analysis, machine learning, parallel computing, data visualization etc.

For those who have experience with python or C language, it’ll not be a big deal to adopt with the Julia programming concepts.

Are you new to programming? Wanna start from python? Don’t worry. I got you covered. Here is an ultimate guide for python beginners.

Why You Should Learn Julia Programming?

Before starting to learn a programming language which is not so popular, one of the main question that will come into your mind will be “should i learn Julia in 2020?” or “is Julia worth learning?”

The answer for this question is depends on what you intend to get out of learning Julia programming.

If you have a passion for programming and thinking long term, It’s highly recommend learning Julia now. You can read this entire quora thread for more suggestions about learning Julia programming in 2020. Moving on.

Julia vs Python

Julia Programming
Language
Python Programming Language
SpeedJulia was developed with high performance in mind. Julia is much faster than python and it has an execution speed close to c programming language. Python is fast but not fast as Julia. But there are ways to speed up. Such as by using external libraries, third-party JIT compilers (PyPy) etc.
Array IndexingIn Julia programming, arrays are 1 indexed. Python arrays are 0 indexed. Most of the programming languages have 0 based array indexing.
LibrariesSince Julia is a relatively new language and it has a slow adaptation curve Julia has limited libraries. Python has a massive amount of libraries that we can use to do our tasks.
LicenseOpen source with a MIT license.Open source with  Python a Software Foundation License
SupportJulia has a very supportive, ever growing and quite small  community.  Since python was lived for years now, when compared with Julia it has a huge community with great support.
Julia vs Python

That’s enough of boring stuff. Now, let’s get into the fun part of this Julia tutorial.

Downloading and Installing Julia

Julia language official website (Julia tutorial)
Julia language official website
  • Head over to the download section.
Downloading Julia
Downloading Julia
  • Select the installer that suits for your operating system. (In my case i’m using windows operating system. Therefore i’m going with 64-bit (installer) .exe installer.)
Downloading Julia for windows
Downloading Julia for windows
  • Once the download completed. Open the Julia installer by double clicking on it.
Julia installer for windows
Julia installer for windows
  • Select a installation directory of your choice and click next. Then it will ask you some additional tasks to perform such as creating a start menu entry, creating a desktop shortcut. Select them as your wish and click next.
Installing Julia tutorial
Installing Julia tutorial
  • Then the installation process will start.
Installation of Julia
Installation of Julia
  • Wait until the process to finish and click on finish to end the process.
Finished Julia installation
Finished Julia installation

How to Add and Run Julia in Jupyter Notebook

  • First, install jupyter on your system using the the below command.
pip install jupyter
pip install jupyter

Please Note – In the above screenshot, i’m getting all those “requirement already satisfied” messages because my PC already have jupyter installed. If you are running the command for the first time you’ll see something different.

  • Once jupyter installed, go to the installed directory of Julia and open up the Julia REPL. (During the installation, if you ticked on the creating a start menu entry option or creating a desktop shortcut option you can run the Julia REPL from those places too.)
Julia REPL
Julia REPL
  • Then run the following to install the necessary packages.
using Pkg
Pkg.add("ZMQ")
Pkg.add("IJulia")
Pkg.update()

While running the above commands if you get an error as below,

SystemError: opening file "C:\\Users\\<your user name>\\.julia\\registries\\General\\Registry.toml": No such file or directory

Deleting C:\Users\<your user name>\.julia\registries\General worked for me. [Source]

installing the necessary packages for jupyter notebook
installing the necessary packages for jupyter notebook
  • Now open Windows CMD window and run the following command to open jupyter notebook.
jupyter notebook
Opening jupyter notebook in windows CMD
Opening jupyter notebook in windows CMD
  • In the opened jupyter notebook window click on New > Julia.
Running Julia in jupyter notebook
Running Julia in jupyter notebook
  • This will open a new windows where you can start coding in Julia.
Julia programming in jupyter notebook

How to Run Julia from Command Line

There are two ways to run Julia from command line.

  1. Using the include() function.
  2. By changing the default ‘opens with’ program to Julia REPL.

Using the include() function

  • First open your favorite text editor and write your program. Save the file with a .jl extension. (Julia files ends with .jl extension.)
  • Now open the Julia REPL and execute the script as shown below. (Make sure to replace every backward slash with forward slash.)
Executing Julia scripts using the command line
Executing Julia scripts using the command line

By changing the default ‘opens with’ program to Julia REPL.

  • Create your script using your favorite text editor and save it with a .jl extension.
  • Next right click on the script file and select ‘opens with’ option.
properties window of a Julia file
properties window of a Julia file
  • Next change the default opens with program to Julia REPL.
  • Save the changes and close the properties window.
  • Double click on the script file to execute. (If your script file open and close as soon as you double click on the file, add readline() function to the end of your script.)
Executing Julia scripts using command line

Now as we know how to download and install Julia, Let’s dive into the real coding stuff with Julia language.

Please note that during this entire Julia tutorial i’m going to use the jupyter notebook to execute and demonstrate Julia code.

Printing “Hello World” in Julia Programming Language

There are two ways to print output on your screen using Julia language.

You can use either print() function or println() function to print output on your screen.

Difference between these two functions is that when you use println() function it print’s the string and move the cursor to a new line.

When you use print() function it print’s the string and does not move the cursor to a new line.

Hello World in Julia language
Hello World in Julia language

Variables In Julia Programming

In Julia language we don’t need to state the variable type.

All we need to assign is a name for the variable, value of the variable and the equal sign. Julia can figure out the type of the variable.

Variables in Julia are case sensitive.

Variables in Julia
Variables in Julia

After assigning a value to a variable we can reassign a different type of value to the exact same variable.

 Reassigning variables in Julia programming

Comments In Julia Programming

Comments are the lines in a Julia script  that are ignored by the compiler at the time of execution.

You can add a single line comment in Julia by adding a “#” sign in front of your desire comment.

# this is a single line comment

Multi-line comments can be added by enclosing the desired comment in between #= and =#

#= 
this is 
a 
multi
line comment
in julia
=#

Since we’ve done taking about the Julia variables in this Julia tutorial, now let’s talk about the arithmetic operations in Julia programming language.

Arithmetic Operations In Julia Programming

Arithmetic operations are same as other programming languages such as python. We can use the typical signs to do mathematical operations in Julia language.

Addition

Sum of two numbers can be get using ‘+’ sign.

Addition in Julia

Subtraction

We can get the difference between two numbers using the ‘-‘ sign.

Subtraction in Julia

Product

To get the product value of two numbers we can use the ‘*’ sign.

Multiplication in Julia

Power

If you want to calculate the power values of a number you can use the ‘^’ sign. In python we are using two asterisk signs (**) to get the power value.

Getting the power value of numbers in Julia

Modulus

We can get the modules of two numbers using the ‘%’ sign.

Getting the modulus of two numbers in Julia

Division

Use the ‘/’ sign to divide two numbers.

Division in Julia

Strings In Julia Programming

Strings are sequence of characters. There are two ways to represent strings in Julia programming.

  1. Using single quotes
  2. Using triple quotes
single_quote_string = "This is a string"
double_quote_string = """This is a string"""

Look at the below example.

String error in Julia

In the above code we are getting an error because the compiler was unable to find the termination point of the string. For such cases we need to use the triple quote delimitation.

Julia strings using triple quotes
Julia strings using triple quotes

We can extract characters from a string by calling the index value of those characters. Note that in Julia indexing starts at 1.

extracting characters from a string
extracting characters from a string

Single quotes (‘ ‘) define a character in Julia programming. In python there is no such thing as character data type. A single character is a string. But in Julia there is a data type as character.

Character data type in Julia
Character data type in Julia

String Interpolation

In simple string interpolation means inserting variable values into strings. There re few ways to do this Julia language.

We can use the ‘$’ sign to insert variables into strings.

String Interpolation in Julia using '$' sign
String Interpolation in Julia using ‘$’ sign

We can also evaluate expression within a string.

Evaluate expression within a string in Julia
Evaluate expression within a string in Julia

String Concatenation

We can use the above mentioned string interpolation or the ‘*’ sign to concatenate or in simple terms combine strings in Julia.

String Concatenation in Julia
String Concatenation in Julia

We can also use the string() function to concatenate strings in Julia. string() function can also be used to convert non-string inputs in strings.

String Concatenation in Julia using string() function
String Concatenation in Julia using string() function

Now we are going to talk about the Julia data structures in this Julia tutorial article. Data structures are different ways of arranging data in a computer system. Julia language also have different type of data structures.

Data Structures In Julia Programming

Dictionaries in Julia

These are unordered data structures. You can create a dictionary in Julia by using the Dict() method.

Dictionaries in Julia
Dictionaries in Julia

Each letter and number is a key and value pair. We can add new key and value pairs to the dictionary as below.

Adding entries to dictionary in Julia
Adding entries to dictionary in Julia

In the above example, we are adding a new key as “d” with the value “4” for the dictionary named as “dict”.

We can extract the values using it’s keys. For example let’s say we need the value of key “c”. You can get it as below.

Extracting values from dictionaries in Julia
Extracting values from dictionaries in Julia

To delete a key from the dictionary we can use the pop! function.

Deleting a key from the dictionary in Julia
Deleting a key from the dictionary in Julia

If you try to access dictionary items using indexes you will get an error because they are unordered.

KeyError: key 1 not found
KeyError: key 1 not found

Tuples In Julia Programming

These are indexable, ordered data structures. In Julia tuples are created using parentheses “()”.

Tuples in Julia
Tuples in Julia

We can access elements inside a tuple by calling the index value of that specific element. Remember that in Julia Array indexing starts from 1.

Accessing elements from a tuple in Julia
Accessing elements from a tuple in Julia

Tuples are immutable data structures. therefore we can not update the tuple once we created.

MethodError: no method matching setindex!(::NTuple{5,String}, ::String, ::Int64)
MethodError: no method matching setindex!(::NTuple{5,String}, ::String, ::Int64)

Arrays In Julia Programming

Arrays are ordered, mutable (which means we can edit after creation) and can hold duplicate values.

These are N-Dimensional containers with rows and columns.

Just as variables arrays can hold elements of any data type. We don’t need to state the data type, Julia can figure out the data type include in the array.

Square brackets”[]” are used to create arrays in Julia programming.

Basically there are three type of arrays.

  • 1 dimensional arrays
  • 2 dimensional array
  • 3 dimensional array

1 Dimensional Arrays

These are arrays contains either a row or a column. In Julia 1D arrays are known as Vectors. We can add elements to the beginning or at the end of these arrays.

1 dimensional arrays in Julia
1 dimensional arrays in Julia

Number circled in red in the above image represents the dimension of the array.

Creating 1D Arrays in Julia Programming

1D arrays can be create by writing the elements of the array within square brackets by separating each element with a comma (,) or a semicolon (;).

Creating 1D Arrays in Julia Programming
Creating 1D Arrays in Julia Programming
Accessing 1D Array Elements in Julia Programming

We can access 1D array elements using the index value of the respective element.

Accessing 1D Array Elements in Julia Programming
Accessing 1D Array Elements in Julia Programming

We can also use ‘true’ and ‘false’ boolean values to access array elements.

Accessing 1D Array Elements using boolean values in Julia Programming
Accessing 1D Array Elements using boolean values in Julia Programming

If you want to access multiple elements at once, you can use multiple index values at once.

Access multiple elements at once in an array
Access multiple elements at once in an array
Adding element to 1D Arrays in Julia Programming

To add elements into an array we can use the push!() method.

Adding elements into an array in Julia
Adding elements into an array in Julia

If you want to add an element at the beginning of an array, you can use the pushfirst!() method.

Using the pushfirst() method in Julia
Using the pushfirst() method in Julia
Updating Existing Elements in a 1D Array Julia Tutorial

As mentioned at the beginning arrays in Julia language are mutable data structures. That means we can modify the content within an array.

Updating Existing Elements in a 1D Array Julia Tutorial
Updating Existing Elements in a 1D Array Julia Tutorial
Removing Elements from a 1D Array In Julia Programming

Use the pop!() method to remove and element from an array in Julia. This will remove the last element from the 1D array.

Removing Elements from a 1D Array using pop!()
Removing Elements from a 1D Array using pop!()

To remove the first element from an array use the popfirst() method.

Using popfirst() to remove first of an array in Julia
Using popfirst() to remove first of an array in Julia

Use empty!() method to delete all the elements of an array.

Using empty!() to remove all elements from an array in Julia
Using empty!() to remove all elements from an array in Julia

2 Dimensional Arrays

In Julia a 2D array is known as a Matrix. 2D arrays contain tabular representation of data.

2 dimensional arrays in Julia
2 dimensional arrays in Julia

Number circled in red in the above image represents the dimension of the array.

Creating 2D Arrays in Julia Programming

In order to create a 2D array in Julia you can write a set of elements without commas and then another set of elements without commas. Then you can separate the two element sets using a single semicolon (;).

Creating 2D arrays in Julia
Creating 2D arrays in Julia
Accessing 2D Array Elements in Julia Programming

We can access elements in 2D arrays using indexes. So let’s say we have a 2×2 matrix array. If we want to access the second element of the second column we can access it as below.

Accessing 2D Array Elements in Julia
Accessing 2D Array Elements in Julia

We can also use the getindex() function to access 2D array elements in Julia.

Using getindex() function to access 2D array elements in Julia
Using getindex() function to access 2D array elements in Julia
Adding element to 2D Arrays in Julia Programming

To add elements into a 2D arrays we can just combine the two arrays as below.

Adding element to 2D Arrays in Julia Programming
Adding element to 2D Arrays in Julia Programming
Updating Existing Elements in a 2D Array Julia Tutorial

We can use the index value of the element that we want to update in order to update elements in a 2D array.

Updating Existing Elements in a 2D Array Julia Tutorial
Updating Existing Elements in a 2D Array in Julia
Removing Elements from a 2D Array In Julia Programming

2D arrays and other multidimensional arrays does not allow us to delete a specific element from the matrix because they need to maintain the row and column order.

Workaround for this is, you can either assign value ‘0‘ or ‘undef‘ to the elements that you want to delete.

assign value '0' to 2D array elements
assign value ‘0’ to 2D array elements
assigning 'undef' to 2D array elements
assigning ‘undef’ to 2D array elements

3 Dimensional Arrays

3D arrays are known as multidimensional arrays in Julia. We can use the  ‘cat’ command to create 3D arrays.

UndefKeywordError: keyword argument dims not assigned error in Julia
UndefKeywordError: keyword argument dims not assigned error in Julia

In the above image you can see that even though we used the  ‘cat’ command to create a 3D array, we are getting an error saying “UndefKeywordError: keyword argument dims not assigned“.

This is because we are missing the ‘dims‘ keyword argument.

‘dims’ keyword argument can take tuple or a series of integer arguments which is corresponding to the lengths in each dimension.

When we assign a value to the ‘dims‘ keyword an array of that dimension will be created.

3 dimensional arrays in Julia
3 dimensional arrays in Julia
Creating 3D Arrays in Julia Programming

As mentioned above we can use the ‘cat’ command together with the ‘dims’ keyword to create 3D arrays in Julia.

Creating 3D Arrays in Julia Programming
Creating 3D Arrays in Julia Programming
Accessing 3D Array Elements in Julia Programming

Same as other dimensional arrays we can use index values to access elements in a 3D array.

Accessing 3D Array Elements in Julia Programming
Accessing 3D Array Elements in Julia Programming

If you can’t understand the indexing of array row and columns when assigning elements take a look at the below diagram.

Array Rows and Columns Indexing
Array Rows and Columns Indexing

Adding element to 3D Arrays in Julia Programming

This is same as adding elements to 2D arrays.

Adding element to 3D Arrays in Julia
Adding element to 3D Arrays in Julia
Updating Existing Elements in a 3D Array Julia Tutorial

This is also same as updating elements in a 2D array.

Updating Existing Elements in a 3D Array in Julia
Updating Existing Elements in a 3D Array in Julia
Removing Elements from a 3D Array In Julia Programming

As mentioned above 2D and multidimensional arrays does not allow us to delete a specific element from the array. We can assign value ‘0‘ or ‘undef‘ to the elements that you want to delete.

Removing Elements from a 3D Array In Julia
Removing Elements from a 3D Array In Julia

We have completed the main type of data structures available in Julia language. Now in this Julia tutorial we are going to learn about the loops in Julia language.

Loops in Julia Language

while Loop in Julia Programming

Syntax for the while loop is,

while loop syntax for Julia language
while loop syntax for Julia language

We can use while loop count or to iterate over an array.

Counting numbers using while loop in Julia
Counting numbers using while loop in Julia

In the above image, while loop evaluates the expression “n < 10” and as long as it’s true it will evaluate the loop body. Once the condition become false it will stop evaluating the body and end the loop.

Looping over an array using while loop in Julia
Looping over an array using while loop in Julia

Above image shows you how to loop through an array using the while loop. while loop evaluates the condition “i <= length(array)”. while this condition is true the loop will iterate over the array and evaluate the loop body.

Once the condition become false it will stop evaluating the body and end the loop.

for Loop in Julia Programming

Syntax of the for loop is,

for loop syntax for Julia language
for loop syntax for Julia language

Let’s go through a simple example.

for loop in Julia
for loop in Julia

In the above diagram, 1:10 is known as a range object which represent the number sequence from 1 to 10. for loop iterate over these 10 numbers and assign each number into the variable ‘n’.

Next it will print each value assigned into the variable ‘n’.

Below image shows you how to loop through an array using the for loop.

loop through an array using the for loop in Julia
loop through an array using the for loop in Julia

Instead of ‘in‘ keyword, we can also use ‘‘ symbol in the for loop.

'∈' symbol in the for loop
‘ symbol in the for loop

Conditionals In Julia Programming

Now we are going to talk about the conditionals in Julia language. Conditional are used to make decisions in our code.

if, elseif and else statements

In the above example there are two variables as ‘a‘ and ‘b‘ which equates to 10 and 20 respectively.

Next we are starting the if statement.

First, it check if a is less than b, if this condition returns false then it will jump into the elseif statement. It will check if a is greater than b.

If both the conditions returned false, it will do whatever stated in the else condition and end the condition check.

During this condition check if any of the testing conditions returned true, it will stop the condition check and do what ever stated in the corresponding block.

Ternary Operator In Julia Programming

Ternary operator is used in occasions where a conditional choice between single expression values is required. Instead of typing long block of codes you can use ternary operator to make it single line. So in simple terms ternary operator is a less wordy if..else statement. Look at the example below.

Ternary Operator In Julia
Ternary Operator In Julia

In the above example, there are two variables as ‘a‘ and ‘b‘ with values 10 and 20 respectively. In the third line we have the ternary operation. Before the ‘?’ sign we have the condition of our operation.

After the ‘?’ operation first we have the ‘execute if true’ code, colon and the ‘execute if false’ code.

In my case, first it check if a is lesser than b. Since a is lesser than b it will print ‘less than‘. We can’t use elseif condition here. If the above condition (a < b) return false it will print ‘not less than‘ no matter what.

syntax: space required before "?" operator
syntax: space required before “?” operator

Please note that as shown in the above image, space between the ‘?’ sign is required in order to successfully execute the code. If not an error will be raised.

In this Julia tutorial we have talked about many basic concepts up to this point. Now we are going to talk about little bit of an advanced topic. It’s called ‘Functions’.

Functions In Julia Programming Tutorial

Functions are reusable collection of codes. In Julia functions are declared by using the function and end keywords. Look at the example below.

Functions in Julia
Functions in Julia

We can also declare function using a single line of code. In order to do this first we have to give the name of the function followed by the set of input arguments within parenthesis. Then the function body in the right side of the equal sign.

declaring function in single line Julia
Declaring function in single line Julia

Julia functions are first-class objects. Therefore they can be assigned to variables. We can also create function without a function name. These are called anonymous functions in Julia.

anonymous functions in Julia
anonymous functions in Julia

In anonymous functions, we write our input variable (in this case name) to the left of ‘->‘ symbol. On the right side we write the function value (in this case ‘println(“My name is $name”)‘). This whole thing is assigned to a variable (in this case ‘a‘).

So when calling an anonymous function we call it by using the assigned variable as shown in the above image.

From here on i’m using the Julia REPL for code demonstrations purposes in this Julia tutorial.

How to Use Packages In Julia Programming

At the time of writing Julia ecosystem contains over 3000 packages. You can check all the available packages from here or here.

How to Install a Package in Julia

  • Open Julia REPL.
Julia REPL
  • Type the below command and press enter. This command says the REPL to use the Julia package manager.
using Pkg
  • Next, type the below command together with the package name that you want to install.
Pkg.add("package name here")
#for example
Pkg.add("Flux")
How to Install a Package in Julia
How to Install a Package in Julia

Wait few minutes until the installation succeed and you are good to go.

In order to use the installed package in your script you can use the ‘using‘ keyword.

So that wrap up all the basics that you need to know in order to proceed with advanced stuff. I know that this is a huge article. But I hope you learned something and enjoyed this ultimate Julia tutorial.

Here is a quick suggestion, bookmark this article in your browser and use this as an cheat sheet until you are comfortable with the basics in Julia programming.

For more advanced and in-depth explanations for the topics discussed here you can visit the official documentation of Julia language from here.

Write A Comment