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 |
|Python Programming Language|
|Speed||Julia 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 Indexing||In Julia programming, arrays are 1 indexed.||Python arrays are 0 indexed. Most of the programming languages have 0 based array indexing.|
|Libraries||Since 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.|
|License||Open source with a MIT license.||Open source with Python a Software Foundation License|
|Support||Julia 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.|
That’s enough of boring stuff. Now, let’s get into the fun part of this Julia tutorial.
Downloading and Installing Julia
- Go to the official website of Julia language.
- Head over to the download section.
- 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.)
- Once the download completed. Open the Julia installer by double clicking on it.
- 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.
- Then the installation process will start.
- Wait until the process to finish and click on finish to end the process.
How to Add and Run Julia in Jupyter Notebook
- First, install jupyter on your system using the the below command.
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.)
- 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]
- Now open Windows CMD window and run the following command to open jupyter notebook.
- In the opened jupyter notebook window click on New > Julia.
- This will open a new windows where you can start coding in Julia.
How to Run Julia from Command Line
There are two ways to run Julia from command line.
- Using the include() function.
- 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.)
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.
- 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.)
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.
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.
After assigning a value to a variable we can reassign a different type of value to the exact same variable.
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.
Sum of two numbers can be get using ‘+’ sign.
We can get the difference between two numbers using the ‘-‘ sign.
To get the product value of two numbers we can use the ‘*’ sign.
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.
We can get the modules of two numbers using the ‘%’ sign.
Use the ‘/’ sign to divide two numbers.
Strings In Julia Programming
Strings are sequence of characters. There are two ways to represent strings in Julia programming.
- Using single quotes
- Using triple quotes
single_quote_string = "This is a string" double_quote_string = """This is a string"""
Look at the below example.
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.
We can extract characters from a string by calling the index value of those characters. Note that in Julia indexing starts at 1.
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.
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.
We can also evaluate expression within a string.
We can use the above mentioned string interpolation or the ‘*’ sign to concatenate or in simple terms combine strings 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.
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.
Each letter and number is a key and value pair. We can add new key and value pairs to the dictionary as below.
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.
To delete a key from the dictionary we can use the pop! function.
If you try to access dictionary items using indexes you will get an error because they are unordered.
Tuples In Julia Programming
These are indexable, ordered data structures. In Julia tuples are created using parentheses “()”.
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.
Tuples are immutable data structures. therefore we can not update the tuple once we created.
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.
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 (;).
Accessing 1D Array Elements in Julia Programming
We can access 1D array elements using the index value of the respective element.
We can also use ‘true’ and ‘false’ boolean values to access array elements.
If you want to access multiple elements at once, you can use multiple index values at once.
Adding element to 1D Arrays in Julia Programming
To add elements into an array we can use the push!() method.
If you want to add an element at the beginning of an array, you can use the pushfirst!() method.
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.
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.
To remove the first element from an array use the popfirst() method.
Use empty!() method to delete all the elements of an array.
2 Dimensional Arrays
In Julia a 2D array is known as a Matrix. 2D arrays contain tabular representation of data.
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 (;).
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.
We can also use the 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.
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.
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.
3 Dimensional Arrays
3D arrays are known as multidimensional arrays in Julia. We can use the ‘cat’ command to create 3D arrays.
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.
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.
Accessing 3D Array Elements in Julia Programming
Same as other dimensional arrays we can use index values to access elements in a 3D array.
If you can’t understand the indexing of array row and columns when assigning elements take a look at the below diagram.
Adding element to 3D Arrays in Julia Programming
This is same as adding elements to 2D arrays.
Updating Existing Elements in a 3D Array Julia Tutorial
This is also same as updating elements in a 2D array.
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.
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,
We can use while loop count or to iterate over an array.
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.
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,
Let’s go through a simple example.
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.
Instead of ‘in‘ keyword, we can also use ‘∈‘ 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.
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.
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.
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.
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.
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
How to Install a Package in Julia
- Open Julia REPL.
- Type the below command and press enter. This command says the REPL to use the Julia package manager.
- 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")
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.