Julia Slides
Julia Slides
Markus Kuhn
https://www.cl.cam.ac.uk/teaching/2324/TeX+Julia/
5 / 29
Installing Julia
Download the current stable release (e.g. v1.9.3) from:
https://julialang.org/downloads/
Windows: Run the 64-bit installer (e.g., julia-1.9.3-win64.exe), then add
“C:\Program Files\Julia-1.9\bin” to your PATH environment variable.
Alternatively: using the Microsoft Store or “winget install julia -s msstore” will install Julia
via the new Juliaup update manager. Also: install Windows Terminal and call Julia inside that, for
much better terminal-emulation behaviour than in cmd.exe.
Most of “Base” and “Standard Library” are written in Julia, with some C. The
@less macro followed by a function call displays the called method in the Julia
source code, e.g.
julia> @less exit()
exit() = exit(0)
shows that exit() just calls exit(0), while providing an integer exit code calls
the internal C function jl_exit:
julia> @less exit(0)
exit(n) = ccall(:jl_exit, Cvoid, (Int32,), n)
7 / 29
Basic REPL use
Invoking julia without a script.jl filename prints a banner and starts the
REPL. Enter Julia expressions and it will display the result:
$ julia
_
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.9.3 (2023-08-24)
_/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release
|__/ |
julia> 6*7
42
Press one of the keys ? ] ; to switch the julia> REPL prompt into one
of these alternate REPL modes: help mode, package manager, shell mode:
help?> exit
(@v1.9) pkg> status
shell> date
Press backspace to leave each mode and return to the julia> prompt.
Type Ctrl-D or exit() to leave julia.
8 / 29
Installing packages
Julia’s Standard Library does not contain e.g. plotting, audio or
digital-signal-processing functions, but add-on packages that provide
these (and their dependencies) can be installed easily from the REPL.
Hit the ] key to enter pkg mode, then type e.g.
julia> a[3,2];
Semicolons equal line feeds:
julia> a = [8 1 6 julia> ans
3 5 7 9
4 9 2] The REPL normally prints the value returned
by each expression entered (assignment returns
3Ö3 Matrix{Int64}: the value assigned). Following an expression
8 1 6 with a semicolon suppresses this.
3 5 7 The value of the last expression evaluated in
4 9 2 the REPL is also assigned to variable ans.
11 / 29
Julia vectors
12 / 29
Julia range objects
start :stop and start :step :stop generate a range of numbers:
-1:3 == [-1, 0, 1, 2, 3]
3:0 == Int64[]
1:3:12 == [1, 4, 7, 10]
3:-0.5:1 == [3.0, 2.5, 2.0, 1.5, 1.0]
The colon actually generates a range object, which behaves like a vector when used like one. The
collect function copies that emulated vector into a real vector in memory.
Loop example:
julia> b = 0; for i in 1:10; b += i; end; b
55
Alternatively:
range(1, length=10) == 1:10
range(1, step=2, stop=10) == 1:2:10
Vectors and ranges as matrix indices select several rows and columns.
When used inside a matrix index, the variable end provides the highest
index value: a[end, end-1] == 9.
Using just “:” is equivalent to “1:end” and can be used to select an
entire row or column.
13 / 29
Row and column selection
Select rows, columns and Matrices can also be accessed as a
submatrices of a: 1-dimensional vector:
julia> a[:,:] julia> a[1:5]
3Ö3 Matrix{Int64}: 5-element Vector{Int64}:
8 1 6 8
3 5 7 3
4 9 2 4
1
julia> a[1,:] 5
3-element Vector{Int64}:
8 julia> a[6:end]
1 4-element Vector{Int64}:
6 9
6
julia> a[:,1] 7
3-element Vector{Int64}: 2
8
3 julia> a[1:4:9]
4 3-element Vector{Int64}:
8
julia> a[2:3,1:2] 5
2Ö2 Matrix{Int64}: 2
3 5 Julia matrices use column-major storage
4 9 order, like Fortran/MATLAB/R, unlike C.
14 / 29
Element-wise operators and broadcasting
Prefix any operator with . to apply it element-by-element to matrices and
vectors. For element-wise function calls, insert dot before opening parenthesis.
julia> [1 2 3] + 5
ERROR: MethodError: julia> 2 .^ [1 2 3]
For element-wise addition, use 1Ö3 Matrix{Int64}:
broadcasting with dot syntax: 2 4 8
array .+ scalar
julia> sqrt.([4 9 16])
julia> [1 2 3] .+ 5 1Ö3 Matrix{Float64}:
1Ö3 Matrix{Int64}: 2.0 3.0 4.0
6 7 8
Dotted operators also grow (broadcast) vectors and matrices along singleton
dimensions, until both operands have the same dimensions:
julia> [8 1 6; 3 5 7] .+ [10; 20]
2Ö3 Matrix{Int64}:
18 11 16
23 25 27
15 / 29
Combining matrices and vectors
Use [ ] to build new matrices, where ; joins submatrices vertically (dimension
1), space (or ;;) joins them horizontally (dimension 2), ;;; joins them in
dimension 3, etc. The , does not join matrices or vectors, it separates elements.
• • • • • • •
• • •
• • • •
• • • •
• • •
· • • • • =
• • • •
• • • • • • • • • • •
• • • • • • •
17 / 29
Review: matrix multiplication
• • • •
• • • •
• • • •
·
• • • • • • •
• • •
• • • •
• • •
=
• • • •
• • • • • • •
• • • • • • •
17 / 29
Review: matrix multiplication
• • • •
• • • •
• • • •
· k
• • • • • • •
• • •
• • • •
• • •
• • • •
• • • • • • •
• • • • • • •
17 / 29
Review: matrix multiplication
• • • •
• • • •
• • • •
· k
• • • • • • •
• • •
• • • •
• • •
• • • •
• • • • • • •
• • • • • • •
17 / 29
Review: matrix multiplication
• • • •
• • • •
• • • •
· k
• • • • • • •
• • •
• • • •
• • •
• • • •
• • • • • • •
• • • • • • •
17 / 29
Review: matrix multiplication
• • • •
• • • •
• • • •
· k
• • • • • • •
• • •
• • • •
• • •
• • • •
• • • • • • •
• • • • • • •
17 / 29
Review: inner and outer product of vectors
•
•
• • • • ·
• =
18 / 29
Review: inner and outer product of vectors
•
•
• • • • ·
• =
• = •
•
18 / 29
Review: inner and outer product of vectors
•
•
• • • • ·
• =
• = •
•
18 / 29
Review: inner and outer product of vectors
•
•
• • • • ·
• =
• = •
•
18 / 29
Review: inner and outer product of vectors
•
•
• • • • ·
• =
• = •
•
18 / 29
Review: inner and outer product of vectors
•
•
• • • • ·
• =
• = •
•
18 / 29
Matrix multiplication
19 / 29
Plotting
using Plots
x = 0:20; t = 0:0.1:10;
y = 0.5 .- 0.5*cos.(2*pi * x/20); x = exp.(t * (1im - 1/3));
plot(x, y; line=:stem, marker=:circle, plot(t, [real(x) imag(x)];
legend=false, grid=true,
title="20-point raised cosine") label=["real" "imaginary"])
x = -20:0.5:20;
y = -20:0.5:20;
r = sqrt.(x.^2 .+ y'.^2);
s = sin.(r) ./ r; s[findall(r.==0)] .= 1; heatmap(x, y, s; c=:grays,
wireframe(x, y, s; grid=true) aspect_ratio=1, xlim=x[[1,end]])
21 / 29
Functions
A variant of this audio effect, where each tone is exactly one octave (factor 2 in frequency) from
the next, is known as the Shepard–Risset glissando.
What changes to the parameters would produce that?
23 / 29
Spectrogram of the first 6 s:
24 / 29
Example solution:
using DSP, Plots, WAV
26 / 29
Pluto notebooks
I Web browser + JavaScript based working environment, Julia server
I Notebook is a sequence of “cells”, each with a Julia expression
I Add a new cell by clicking “+” above/below existing cell
I Run a cell by pressing Shift+Enter
I Return value of the expression in a cell is displayed above the cell
I Notebooks can be exported as PDF or static HTML
I Cell can output pretty documentation as Markdown md"..." or
HTML html"..." strings, cell source code can be hidden
Pluto notebooks are “reactive”, like a spreadsheet
I Each global variable can only be assigned to in one cell
I If running that cell changes a global variable, then all other cells that
read that global variable get automatically re-evaluated
I A Pluto notebook is just a Julia script containing the code from all
cell, arranged in the order in which they need to be executed
I The order in which cells appear in the browser does not matter
To run multiple expressions in the same Pluto cell, wrap them in a begin ... end block.
To create a lexical scope for local variables in a cell, use instead let ... end blocks or functions.
27 / 29
Cheatsheet: finding out things in Julia
typeof(...) type of any object
sizeof(...) array dimensions
axes(...) array index ranges
eachindex(...) vector index range
eltype(...) element type of an Array
apropos("keyword") search in documentation for string
methods(open) list all methods for a function
methodswith(Vector{UInt8}) list all methods that accept a type
@show expr show expression and result, return result
dump(...) field types and values of structs
fieldnames(Complex) fieldnames of a struct
Complex{Real}.types types of struct fields
names(Base) names exported by a module
subtypes(AbstractString) list of immediate subtypes of a type
supertype(String) return the supertype of a type