Let's start with a quick overview of the basic syntax, emphasising differences with Python.
In [2]:
x = 3
Out[2]:
In [3]:
# variables can be any unicode characters
α = 3; β = 10
Out[3]:
In [4]:
# aside: last result is stored in 'ans' in the REPL/IJulia
typeof(ans)
Out[4]:
In [5]:
# There are some convenient built-ins
2*π
Out[5]:
In [6]:
x = 3
typeof(x)
Out[6]:
In [7]:
y = 3.0
typeof(y)
Out[7]:
In [8]:
z = 1. + 3.im
typeof(z)
Out[8]:
In [9]:
w = true
typeof(w)
Out[9]:
In [10]:
# division is like in Python 3: Int/Int => Float
5 / 2
Out[10]:
In [11]:
# integer division
div(5, 2)
Out[11]:
In [12]:
# power is ^ not **
5^2
Out[12]:
In [13]:
# use ! instead of not
!true
Out[13]:
In [14]:
# Comparisons can be chained (as in python)
1 != 2 < 3 < 4
Out[14]:
In [17]:
# Strings are double-quoted
s = "This is a string"
# characters are single-quoted
c = 'a'
Out[17]:
In [18]:
# String interpolation with $ (can contain any Julia expression!)
"2 + 2 = $(2 + 2)"
Out[18]:
In [19]:
name = "julia"
"Hi, I'm $name"
Out[19]:
In [20]:
# more complex expressions are wrapped in parentheses
μ = 3
"The sine of $μ is $(sin(μ))"
Out[20]:
In [24]:
# println() adds a newline, print() ommits it
println("x = ", x)
print("x = $x")
In [25]:
# formatted printing
@printf "%d is less than %4.2f" 4.5 5.3
In [26]:
# standard syntax
function f(x)
return 2x^2 + 3x + 1
end
f(3)
Out[26]:
In [27]:
# one-line syntax
f(x) = 2x^2 + 3x + 1
g(x) = f(x) - (2x+1) * (x+1)
g(3.5)
Out[27]:
In [28]:
a = [3, 4, 5]
Out[28]:
In [29]:
typeof(a)
Out[29]:
In Julia these objects are called Array
s. The curly braces indicate type parameters of the Array
type. The first is the type of element contained in the Array
(all must be of the same type) and the second the number of dimensions.
In NumPy this information is stored in attributes of the object rather than the type itself. Python:
>>> a = np.array([3, 4, 5])
>>> a.dtype
dtype('int64')
>>> a.ndim
1
In [30]:
# Array of heterogeneous types (similar to Python list or numpy "object" array)
[3., "hello", 2]
Out[30]:
In [31]:
# [] tries to infer a type, {} is an Any Array
{3, 4, 5}
Out[31]:
In [32]:
# There's type promotion to a common type
[3., 4, 5]
Out[32]:
In [33]:
# Explicitly set the type
Int64[3., 4, 5]
Out[33]:
Square brackets with commas gives a one-dimensional vector. This is printed in a way that treats it as if it were a column vector (although there is in fact no difference between a one-dimensional row vector and column vector).
In [34]:
[1, 2, 3]
Out[34]:
To create explicit matrices, Matlab-style notation is used. If we omit the commas, something different happens: we now obtain a two-dimensional Array
, i.e. a matrix, of size $1 \times n$. [Recall that in the standard notation for matrices, an $m \times n$ matrix has $m$ rows and $n$ columns.]
In [35]:
[1 2 3]
Out[35]:
In [36]:
# Semicolon can be used to write 2-d array literals
a = [1 2 3;
4 5 6]
Out[36]:
In [39]:
# Python-like syntax gives you something different!
a = [[1, 2, 3], [4, 5, 6]]
Out[39]:
In [40]:
# Many numpy-like functions are available for creating arrays:
ones((2, 3))
zeros((2, 3))
trues((2, 3))
falses((2, 3))
Array(Float64, (2, 3)) # uninitialized
# ... and many more.
Out[40]:
It's different than NumPy!
In [43]:
# The first item is at index 1, not 0
l = [3, 4, 5]
l[1]
Out[43]:
The syntax for ranges is similar to that for Python:
In [44]:
# ranges are inclusive at both ends
l[1:2]
Out[44]:
In [45]:
# end must be explicit
l[2:end]
Out[45]:
In [46]:
# indexing from the end
l[1:end-1]
Out[46]:
In [49]:
# append an element
push!(l, 6)
Out[49]:
Ending a function name with "!" is a convention to tell the user that the funciton modifies its input(s).
In [52]:
# types are converted automatically if possible & exact
l = [3, 4, 5]
push!(l, 12.0)
Out[52]:
In [53]:
a = [1.1, 2.2, 3.3]
b = [4.4, 5.5, 6.6]
a + b
Out[53]:
In [54]:
3.5 * a
Out[54]:
By default, operations are matrix operations, not element-wise!
In [55]:
# matrix multiply doesn't work on two vectors:
a * b
In [56]:
# it works if we transpose a:
println(a')
a' * b
Out[56]:
In [57]:
# Instead, there are explicit element-wise operators
a .* b
Out[57]:
In [59]:
# You can do array-wise operations:
a.^2 .+ b.^2
Out[59]:
In [60]:
# unicode dot and cross-products
a ⋅ b
Out[60]:
In [61]:
a × b
Out[61]:
In [62]:
squares = [i^2 for i in [1:2:10, 7]]
Out[62]:
In [63]:
sums = [i+j for i=1:5, j=1:5]
Out[63]:
In [64]:
help(size)
In [65]:
# This also works [note the special mode in the command-line REPL]
?size
In [ ]:
# Shell commands
;ls
In [66]:
# commands in general
run(`echo hello`)
White space in Julia is not significant. Commands on one line can be separated by ;
. Blocks must finish with end
In [68]:
i = 0
while i < 5
print("$i\t")
i += 1
end
In [69]:
total = 0
for i = 1:10
total += i
end
println("Sum is $total")
In [71]:
a = ["hi", "bye"]
for item in a
println(item)
end
Here, 1:10
is a range object which may be iterated over.
In [70]:
typeof(1:10)
Out[70]:
Use help
or ?
to get help:
In [72]:
a = 3
a < 5 && println("Small") # evaluate the second statement only if the first is true; semantics of if-then
a > 10 || println("Small") # semantics of if not-then
In [73]:
a == 3 ? println("Hello") : println("Not true")
In [74]:
(1, 2)
Out[74]:
In [75]:
typeof(ans)
Out[75]:
In [76]:
a, b = 1, 2
Out[76]:
In [77]:
# Dictionaries store mappings
# create an empty dictionary
d = Dict()
Out[77]:
In [81]:
# You can create a dictionary using a literal
d = ["one"=> 1, "two"=>2]
Out[81]:
In [82]:
# Look up values with []
d["one"]
Out[82]:
In [83]:
d["four"] = 4
Out[83]:
In [84]:
# Get all keys
keys(d)
Out[84]:
In [85]:
# Get all values
values(d)
Out[85]:
In [86]:
outfile = open("test.txt", "w")
Out[86]:
In [87]:
for i in 1:10
println(outfile, "The value of i is $i")
end
close(outfile)
In [88]:
;cat test.txt
In [89]:
infile = open("test.txt", "r")
Out[89]:
In [90]:
lines = readlines(infile)
Out[90]:
In [91]:
x = rand(5,5)
Out[91]:
In [92]:
# There's a basic built-in text file reader and writer
writedlm("random.txt", x)
;cat random.txt
In [93]:
y = readdlm("random.txt") # note that tab completion works for files
Out[93]:
In [94]:
# clean uup
;rm random.txt
;rm test.txt