Julia Cheatsheet

REPL Modes

Key Mode Example
(default) Julia 1 + 1
? Help ?sqrt
] Pkg add QuadGK, status, rm Foo
; Shell ls, pwd

Variables & Types

x = 55699
x = 1 + 1im          # complex number (no space before im)
x = 3.14              # Float64
x = true              # Bool

typeof(x)             # check type
eltype(x)             # element type (for arrays)

Arithmetic & Math

2.0^2                 # exponent (not **)
sqrt(9)               # → 3.0 (Float64)
sqrt(Complex(-1.0))   # need complex input for complex result
div(8, 5)             # integer division → 1
8 ÷ 5                 # \div<tab>, same as div()
rem(8, 5)             # remainder → 3
8 % 5                 # same as rem()
abs(-3)               # absolute value

Strings

s = "hello"
"$s world"            # interpolation
"$s" * "!"            # concatenation
length(s)
uppercase(s)
split("a b c")        # → ["a", "b", "c"]

Functions

# Inline / anonymous
f = x -> 2 * x
square = x -> x^2

# Short form
f(x) = 2 * x

# Full form (preferred for non-trivial logic)
function f(x)
    return 2 * x
end

# Optional positional + keyword arguments
# positional optional must come before keywords
function f(x, y=2, z=3; a=4.0, b=5.0)
    println([x, y, z, a, b])
    return x + y + z^a + b
end

f(1)
f(1, 10, b=173, a=77)
f(1, 2, 4, b=173)     # must specify y before z

# Splat a NamedTuple as keywords
opts = (a=5.0, b=3.0)
f(1, 2, 4; opts...)

# Pipe operator
2 |> square           # → 4

# Broadcast (element-wise)
sin.(1:5)
@. sin(1:5)^2         # applies . to every operation

Control Flow

# if / elseif / else
if x > 0
    println("positive")
elseif x == 0
    println("zero")
else
    println("negative")
end

# Ternary
x > 0 ? "pos" : "non-pos"

# for loop
for i in 1:5
    println(i)
end

# while loop
i = 1
while i <= 5
    i += 1
end

# break / continue work as expected

Arrays & Vectors

# 1D (column vector)
v = [1, 2, 3]

# Row vector
r = [1 2 3]

# Concatenation
[v; v]                # vertical (append rows)
[r r]                 # horizontal (append cols)

# Constructors
zeros(3)              # [0.0, 0.0, 0.0]
ones(3)
rand(5)               # uniform [0,1)
randn(5)              # standard normal

# Ranges
r = 1:10              # lazy range
r = range(0.0, 1.0, length=50)
r = range(0.0, 1.0, step=0.1)

# Comprehensions & generators
arr = [x^2 for x in 1:10]
gen = (x^2 for x in 1:10)  # lazy, no memory allocation
collect(gen)                # materialize generator → array

# similar / fill
x1 = similar(arr)
fill!(x1, π)

# Useful operations
push!(v, 4)           # append in-place
pop!(v)               # remove last
append!(v, [5,6])     # append multiple
length(v)
sum(v); prod(v); maximum(v); minimum(v)

# Indexing (1-based)
v[1]                  # first element
v[end]                # last element
v[2:4]                # slice (returns copy)
v[2:end]

# eachindex — always prefer over 1:length(v)
# safe for any index type, offset arrays, etc.
for i in eachindex(v)
    v[i] *= 2
end

# iterate with both index and value
for (i, val) in enumerate(v)
    println("v[$i] = $val")
end

# iterate two arrays together
for (a, b) in zip(v, w)
    println(a + b)
end

# Broadcast
v .^ 2
@. sin(v)^4

Matrices

# Literal syntax (spaces = cols, semicolons = rows)
A = [1 2 3; 4 5 6]   # 2×3 matrix

# Column-based construction
A = [[1,4,7] [2,5,8] [3,6,9]]

# From reshape
A = reshape(1:9, 3, 3)   # NOTE: fills column-major

# Constructors
zeros(3, 3)
ones(2, 4)
rand(3, 3)
randn(3, 3)
Matrix{Float64}(undef, 3, 3)   # uninitialized
Matrix(I, 3, 3)                # identity (using LinearAlgebra)

# Indexing
A[1, 2]               # row 1, col 2
A[:, 1]               # entire first column
A[1, :]               # entire first row

# Transpose
A'                    # adjoint (conjugate transpose)
transpose(A)          # non-conjugate transpose

# Common operations (using LinearAlgebra)
using LinearAlgebra
A * B                 # matrix multiply
A .* B                # element-wise multiply
inv(A)
tr(A)                 # trace
diag(A)               # diagonal elements
det(A)
norm(A)
eigen(A)              # eigendecomposition → .values, .vectors
eigvals(A)
eigvecs(A)
svd(A)                # SVD

# Solve A*x = b
b = rand(3)
x = A \ b

Summation Patterns

N = 10

# Loop
ret = 0.0
for i in 1:N
    ret += 1 / i^2
end

# Array comprehension
ret = sum([1/i^2 for i in 1:N])

# Generator (no intermediate array allocated — preferred)
ret = sum(1/i^2 for i in 1:N)

# Broadcast shorthand
ret = sum(@. 1 / (1:N)^2)

Recursion

# Ternary (concise)
fac(n) = n == 1 ? 1 : n * fac(n - 1)

# Full form with type annotation
function fac(n::Int)
    n < 1 && error("n must be ≥ 1")
    return n == 1 ? 1 : n * fac(n - 1)
end

# Non-integer generalization: use gamma function
using SpecialFunctions
gamma(n + 1)          # equals fac(n) for integer n

I/O

# User input
s = readline()
x = parse(Float64, readline())
n = parse(Int, readline())

# CSV (recommended for tabular data)
using CSV, DataFrames

df = DataFrame(rand(10, 3), :auto)
CSV.write("result.csv", df)
df = DataFrame(CSV.File("result.csv"))

# CSV with options
df = DataFrame(CSV.File("result.dat",
    comment="#", delim=" ", header=false))

# DelimitedFiles (lightweight, no DataFrame needed)
using DelimitedFiles

# Build data row-by-row (e.g. from a solver returning multiple outputs)
# _solver(x) returns a tuple/array; splat it with ...
data = []
for x_now in x_arr
    entry = [x_now, _solver(x_now)...]   # flatten into one row
    push!(data, entry')                   # push as row vector
end
data = vcat(data...)                      # stack into matrix

open("result.dat", "w") do f
    write(f, "# x  y  z\n")
    writedlm(f, data)
end

data2 = readdlm("result.dat", comments=true)

# fetch columns by index
xvec = data2[:, 1]
yvec = data2[:, 2]

# Load a Julia file
include("./myfile.jl")

Plotting (Plots.jl)

using Plots

x = range(0, 2π, length=200)

p = plot(x, sin.(x), label="sin(x)", lw=2)
plot!(p, x, cos.(x), label="cos(x)", linestyle=:dash)

xlabel!("x"); ylabel!("y"); title!("Trig functions")

savefig(p, "fig.png")   # or .pdf, .svg

Introspection & Performance

methods(*)                  # all methods for *
methods(*, [Int, Int])      # filtered by types
@less 2 + 2.0               # view source
@code_llvm 2 + 4.0          # LLVM IR
@code_native 1 + 1          # native assembly
@time f(x)                  # time + allocations
@allocated f(x)             # allocations only
@benchmark f(x)             # (BenchmarkTools.jl)

Further Resources