0% found this document useful (0 votes)
25 views39 pages

Julia Slides

slides on julia

Uploaded by

taiyamxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views39 pages

Julia Slides

slides on julia

Uploaded by

taiyamxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Introduction to Julia

Markus Kuhn

Department of Computer Science and Technology


University of Cambridge

https://www.cl.cam.ac.uk/teaching/2324/TeX+Julia/

julia-slides.pdf 2023-10-08 21:42 e3334db 1 / 29


Technical computing languages
I support rapid prototyping and interactive exploration of numerical
algorithms and data sets
I high-level language (garbage collecting, var-len structures)
I comprehensive support for linear algebra, statistics, and plotting
I main data types: multi-dimensional numeric arrays and matrices
I most operators and functions work on entire matrices
⇒ rarely necessary to write out loops
I use internally highly optimized numerical libraries
(BLAS, LAPACK, FFTW)
I support interactive use via read-evaluate-print loop (REPL)
I interpreted or just-in-time compiled, notebook support
I comprehensive toolboxes/modules/packages for easy access to
standard algorithms from many fields: statistics, machine learning,
image processing, signal processing, neural networks, wavelets,
communications systems, etc.
I very easy I/O for many data/multimedia file formats
I widely used as a visualization and teaching tool
2 / 29
Older contenders
I MATLAB – “matrix laboratory” student tool (University of New
Mexico, 1970s), commercial product since 1984, very widely used
since 1990s in engineering simulations and teaching, initially not a
general-purpose language (e.g., object classes only from 2008,
dictionaries only added in 2022), integrated IDE, since 2000 based
on Java JVM code generation
Campus licence:
https://uk.mathworks.com/academia/tah- portal/the- university- of- cambridge- 666637.html

I Similar to (earlier versions of) MATLAB, subset compatible:


GNU Octave, SciLab, FreeMat
I R – focus on statistics and plotting
https://www.r-project.org/
I Python – a full-featured programming language. Modules:
• numpy – MATLAB-like numerical arrays, fast linear algebra
• matplotlib – MATLAB-like plotting functions
https://matplotlib.org/
• SciPy – scientific computing, Pandas – data analysis, etc.
I others: LuaJIT (SciLua), Perl Data Language (PDL), OCaml (Owl)
R and especially Python become very popular ≈2000–2010, but are much slower than compiled
statically typed C/C++/Fortran, as their dynamic types were intended for interpreted execution. In
HPC applications, they remain mainly configuration/glue languages for C/C++/Fortran libraries.
3 / 29
Julia
Modern, fast, full-featured, compiled, interactive language,
initially created 2009–2012 at Massachusetts Institute of Technology
by J. Bezanson, A. Edelman, S. Karpinski, V.B. Shah.

I MATLAB-inspired syntax (especially much nicer


and compacter array syntax than NumPy)
I not intended to be MATLAB compatible
I combines dynamic and static type systems via multiple dispatch
I just-in-time compiled by LLVM backend
I with some care, Julia code can execute nearly as fast as C/C++
I aims to solve the two-language problem
(versus e.g. Python having to call C/C++ code for performance)
I can also call C, C++, Python, R, Fortran functions
I LISP-like metaprogramming, rich flexible parametric type system
I built-in package manager for easy access to package ecosystem,
version-controlled virtual package environments (“projects”)
I multiple dispatch helps with reusing types across packages
I Backwards-compatible since version 1.0 (2018)
4 / 29
Julia shortcomings
I start-up delay when loading/calling large packages, as they need to
be JIT compiled first (“time to first plot”)
Julia 1.9 now much faster thanks to on-disc cache for pre-compiled object code of packages.
I not aimed at compilation of stand-alone binaries
Possible with PackageCompiler.jl, but requires extra effort and can lead to large
(> 100 MB) binaries.
I not aimed at hard real-time applications: heap memory allocation
and automatic mark-and-sweep garbage collection can introduce
non-deterministic delays
Manual control of memory allocation is possible, but not typical Julia style, and often not
supported by ecosystem packages.
I package ecosystem and package documentation sometimes still less
mature or complete than that of Python, R, MATLAB
But it is very easy to get involved via Pkg.develop and GitHub pull requests.
I diversity of package ecosystem can be confusing initially (e.g.
several competing major plotting libraries), usually more than one
way of doing everything (esp. compared to MATLAB)
Hence this quick introductory tour!

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.

Homebrew: (on macOS or Linux)


$ brew install --cask julia
or
macOS: Install the 64-bit .dmg package, then add to your PATH the path
“/Applications/Julia-1.9.app/Contents/Resources/julia/bin”.

Linux: Download the julia-1.9.3-linux-x86_64.tar.gz tarball and unpack


somewhere convenient, e.g. at /opt/julia-1.9.3 with e.g.
$ sudo bash
# cd /opt && tar xvzf /path/to/julia-1.9.3-linux-x86_64.tar.gz
Then add “/opt/julia-1.9.3/bin” to your PATH environment variable.
6 / 29
Documentation
The Julia documentation at
https://docs.julialang.org/
consists of the core language manual, plus the reference manuals for
I “Base” – the built-in standard functions and types
I “Standard Library” – packages preinstalled with Julia
These reference manuals are autogenerated from “docstrings” embedded
in the source code. You can also read these docstrings from the REPL
help mode with “?function ”.

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.

(@v1.9) pkg> add Plots WAV DSP


(@v1.9) pkg> status
Status `/home/mgk25/.julia/environments/v1.9/Project.toml`
[717857b8] DSP v0.7.8
[91a5bcdd] Plots v1.38.17
[8149f6b0] WAV v1.2.0

Julia’s Pkg manager downloads https://github.com/JuliaRegistries/General and searches in


it for the latest versions of the registered packages you asked to add. [You can also ask for specific
versions (add [email protected]) or add unregistered packages by providing a git URL.]
To modify a downloaded package, use e.g. “dev WAV” to prepare and use a local git clone of that
package in ~/.julia/dev/WAV/. Later use “free WAV” to return to a registered version.
Quick docs: type ? or prefix a pkg-mode command with ?
Full Pkg.jl documentation: https://pkgdocs.julialang.org/
Packages and their metadata are all installed into ~/.julia/ by default. Set the environment
variable JULIA_DEPOT_PATH if you want them elsewhere.
9 / 29
Julia basic types and their literals
Bool false, true
Int, Int8, ..., Int128 123, 1_000_000, UInt128(2)^127
UInt, UInt8, ..., UInt128 0xff, 0x0012, 0b1011, 0o377
Float64, Float32, Float16 .5, 1.0, 3e6, 2.3f9, NaN, -Inf16
Complex{Float64} 0.0 + 1.0im
Rational{Int64} 3//4 + 1//2 == 5//4
Char 'a', '\n', '\u20ac'
String "hi", "I am \"$name\"", "1+1=$(1+1)"
Symbol :test
Vector{Int} = Array{Int,1} [1, 2, 3]
Matrix{Int} = Array{Int,2} [1 2; 3 4]
Tuple{Int64,Char,Bool} (1, 'a', false)
Nothing nothing
Missing missing + 1 == missing
Int and UInt arithmetic is not checked for overflow, like in C: 2^64==0
Use floating-point literals to get floating-point operations: 2.0^64 > 0
Type aliases on 64-bit CPUs: Int = Int64, UInt = UInt64
10 / 29
Julia matrices

Assign a 3 × 3 matrix of integers: Access a single element:


julia> a = [8 1 6; 3 5 7; 4 9 2] julia> a[2,3]
3Ö3 Matrix{Int64}: 7
8 1 6 Vector and matrix indices start at 1. The first
3 5 7 index selects the row, the second the column,
4 9 2 like in linear algebra notation.

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

Vectors are one-dimensional arrays that act in a linear-algebra context


like a vertical/column vector:
julia> b = [1, 2, 3]
3-element Vector{Int64}:
1
2
3
They are different from horizontal/row vectors, which are stored as
two-dimensional 1 × n matrices:
julia> b = [10 20 30]
1Ö3 Matrix{Int64}:
10 20 30

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.

julia> a = [8 1 6; 3 5 7; 4 9 2] julia> [[1,2],[3,3]]


3Ö3 Matrix{Int64}: 2-element Vector{Vector{Int64}}:
8 1 6 [1, 2]
3 5 7 [3, 3]
4 9 2 You can also mask elements:
julia> a .> 5
julia> d = [a[:,end] a[1,:]]
3Ö3 BitMatrix:
3Ö2 Matrix{Int64}:
1 0 1
6 8
0 0 1
7 1
0 1 0
2 6
julia> a[a .> 5] .= 0 ; a
julia> e = [zeros(1,3); a[2,:]']
3Ö3 Matrix{Int64}:
2Ö3 Matrix{Float64}:
0 1 0
0.0 0.0 0.0
3 5 0
3.0 5.0 7.0
4 0 2
16 / 29
Review: matrix multiplication

   
• • •   • • • •

 • • • 
 • • • • 
 • • • • 


 • • • 
 ·  • • • •  = 
 • • • • 

 • • •  • • • •  • • • • 
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and
the corresponding column in the second factor

17 / 29
Review: matrix multiplication

 
• • • •
 • • • • 
• • • •
·
   
• • • • • • •

 • • • 


 • • • • 


 • • • 
 = 
 • • • • 

 • • •   • • • • 
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and
the corresponding column in the second factor

17 / 29
Review: matrix multiplication

 
• • • •
 • • • • 
• • • •
· k
   
• • • • • • •

 • • • 


 • • • • 


 • • • 


 • • • • 

 • • •   • • • • 
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and
the corresponding column in the second factor

17 / 29
Review: matrix multiplication

 
• • • •
 • • • • 
• • • •
· k
   
• • • • • • •

 • • • 


 • • • • 


 • • • 


 • • • • 

 • • •   • • • • 
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and
the corresponding column in the second factor

17 / 29
Review: matrix multiplication

 
• • • •
 • • • • 
• • • •
· k
   
• • • • • • •

 • • • 


 • • • • 


 • • • 


 • • • • 

 • • •   • • • • 
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and
the corresponding column in the second factor

17 / 29
Review: matrix multiplication

 
• • • •
 • • • • 
• • • •
· k
   
• • • • • • •

 • • • 


 • • • • 


 • • • 


 • • • • 

 • • •   • • • • 
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and
the corresponding column in the second factor

17 / 29
Review: inner and outer product of vectors

Special cases of matrix multiplication

 

  • 
• • • • ·
 • =

Row vector times column vector:

18 / 29
Review: inner and outer product of vectors

Special cases of matrix multiplication

 

  •  
• • • • ·
 • =
 • = •

Row vector times column vector:

18 / 29
Review: inner and outer product of vectors

Special cases of matrix multiplication

 

  •  
• • • • ·
 • =
 • = •

Row vector times column vector: scalar product, dot product

18 / 29
Review: inner and outer product of vectors

Special cases of matrix multiplication

 

  •  
• • • • ·
 • =
 • = •

Row vector times column vector: scalar product, dot product


 

 •  
 ·
 •  • • • •

Column vector times row vector:

18 / 29
Review: inner and outer product of vectors

Special cases of matrix multiplication

 

  •  
• • • • ·
 • =
 • = •

Row vector times column vector: scalar product, dot product


   
• • • • •
 •    • • • • 
 ·
 •  • • • • =
 •

• • • 
• • • • •

Column vector times row vector:

18 / 29
Review: inner and outer product of vectors

Special cases of matrix multiplication

 

  •  
• • • • ·
 • =
 • = •

Row vector times column vector: scalar product, dot product


   
• • • • •
 •    • • • • 
 ·
 •  • • • • =
 •

• • • 
• • • • •

Column vector times row vector: matrix of all pair-wise products

18 / 29
Matrix multiplication

Operators on scalars and matrices: Inner and outer vector product:


julia> [2 3 5] * [1 7 11]'
julia> [1 1; 1 0] * [2 3]' 1Ö1 Matrix{Int64}:
2Ö1 Matrix{Int64}: 78
5
2 julia> [2 3 5]' * [1 7 11]
3Ö3 Matrix{Int64}:
julia> [1 2 3] .* [10 10 15] 2 14 22
1Ö3 Matrix{Int64}: 3 21 33
10 20 45 5 35 55

Complex number types: Complex{Int16}, Complex{Float64}, etc.



The imaginary unit vector −1 is available as 1im and and vectors and
matrices can also be complex.
Related functions: real, imag, conj, exp, cis, abs, angle

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"])

Function plot expects a vectors of x coordinates, and a vector or matrix of y


coordinates, one column per curve. Use plot! to add additional curves with
independent x coordinates.
Use savefig("plot2.pdf") to save current figure as graphics file.
20 / 29
2D plotting
using Plots

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]])

Plots.jl manual: https://docs.juliaplots.org/

21 / 29
Functions

To define a new function, for example decibel(x) = 10x/20 , write


function decibel(x)
return 10 .^ (x ./ 20)
end
or simply
decibel(x) = 10 .^ (x ./ 20)
and call as
julia> decibel(40)
100.0
Note that the function needs no type declaration for parameters. Each time the function is called
with a new type, a new method will be JIT compiled for that type signature.
Type annotations using :: are assertions and for type-dependent dispatch.

Default values for positional and keyword parameters:


function decibel(x=0; base::Number=10)
return base .^ (x ./ 20)
end
22 / 29
Example: generating an audio illusion
Generate an audio file with 12 sine tones of apparently continuously
exponentially increasing frequency, which never leave the frequency range
300–3400 Hz. Do this by letting them wrap around the frequency interval
and reduce their volume near the interval boundaries based on a
raised-cosine curve applied to the logarithm of the frequency.
First produce a 2 s long waveform in which each tone raises 1/12 of the
frequency range, then concatenate that into a 60 s long 16-bit WAV file,
mono, with 16 kHz sampling rate. Avoid phase jumps.
Parameters:
fs = 16000; # sampling frequency [Hz]
d = 2; # time after which waveform repeats [s]
n = 12; # number of tones
fmin = 300; # lowest frequency
fmax = 3400; # highest frequency

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

t = 0:1/fs:d-1/fs; # timestamps for each sample point


# normalized logarithm of frequency of each tone (row)
# for each sample point (column), all rising linearly
# from 0 to 1, then wrap around back to 0
l = mod.(((0:n-1)/n) .+ (t/(d*n))', 1);
f = fmin * (fmax/fmin) .^ l; # freq. for each tone and sample
p = 2*pi * cumsum(f, dims=2) / fs; # phase for each tone and sample
# make last column a multiple of 2*pi for phase continuity
p = ((2*pi*floor.(p[:,end]/(2*pi))) ./ p[:,end]) .* p;
s = sin.(p); # sine value for each tone and sample
# mixing amplitudes from raised-cosine curve over frequency
a = 0.5 .- 0.5 * cos.(2*pi * l);
w = sum(s .* a, dims=1)/n; # mix tones together, normalize to [-1, +1]

w = repeat(vec(w), 3); # repeat waveform 3x


m = spectrogram(w, 2048, 1800; fs, window=hamming);
ps = 10 * log10.(power(m)); mx = maximum(ps);
heatmap(time(m), freq(m), ps;
xlabel="time [s]", ylabel="frequency [Hz]",
ylim=(0, fmax*1.1), clim=(mx-47,mx))
savefig("ladder-jl.pdf")
w = repeat(w, 5); # repeat waveform 5x
#wavplay(w, fs);
wavwrite(w, "ladder.wav", Fs=fs); # make audio file
25 / 29
Running Julia code

There are many ways to run Julia code:


I Load script manually from REPL:
julia> include("script.jl")
I Run as script:
$ julia script.jl
I Run as script, then activate REPL (e.g., to manually call functions):
$ julia -i script.jl
I Automatically reload modified source files:
https://github.com/timholy/Revise.jl
I Run from within an IDE, such as Visual Studio Code:
https://code.visualstudio.com/docs/languages/julia
I Jupyter notebooks – for Julia, Python, R, etc.
https://github.com/JuliaLang/IJulia.jl
I Pluto.jl notebooks – reactive notebooks that are Julia scripts
https://github.com/fonsp/Pluto.jl

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

@code_lowered, @code_typed, @code_warntype, @code_llvm,


@code_native show code in different compilation stages,
@edit, @less give easy access to source code.
28 / 29
MATLAB, Julia, NumPy: comparative cheat sheet
MATLAB Julia NumPy

vector size (1,n) [1 2 3] [1 2 3] np.array([1, 2, 3]).reshape(1, 3)


vector size (n,1) [1; 2; 3] [1 2 3]’ np.array([1, 2, 3]).reshape(3, 1)
vector size (n) n/a [1, 2, 3] np.array([1, 2, 3])
j to n step k j:k:n j:k:n np.arange(j, n+1, k)
matrix [1 2; 3 4] [1 2; 3 4] np.array([[1, 2], [3, 4]])
0 matrix zeros(2, 2) zeros(2, 2) np.zeros((2, 2))
1 matrix ones(2, 2) ones(2, 2) np.ones((2, 2))
identity matrix eye(2, 2) I np.eye(2)
diagonal matrix diag([1 2 3]) Diagonal([1, 2, 3]) np.diag([1, 2, 3])
transpose A.’ transpose(A) A.T
complex conj. transpose A’ A’ A.conj()
concat hor. [[1 2] [1 2]] [[1 2] [1 2]] B = np.array([1, 2])
np.hstack((B, B))
matrix to vector A(:) A[:] A.flatten()
flip left/right fliplr(A) reverse(A,dims=2) np.fliplr(A)
broadcast a function f=@(x) x.^2; f(x)=x^2; f.(x) def f(x):
f(x) return x**2
f(x)
element A2,2 A(2, 2) A[2, 2] A[1, 1]
rows 1 to 4 A(1:4, :) A[1:4, :] A[0:4, :]
element-wise multipl. A .* B A .* B A*B
matrix multiplication A*B A*B A@B
...
https://cheatsheets.quantecon.org/
29 / 29

You might also like