Julia Quick Reference & Migration Guide (2025, Julia 1.10+)

Author: Manuel Behrendt Compiled: 26 July 2025

Audience: Mera users, scientists, and users migrating from Python, MATLAB, or IDL.

Julia at a Glance: Julia combines the speed of C, the ease of Python, and the power of multiple dispatch and metaprogramming. It is designed for scientific and technical computing, with a focus on performance and productivity.

Legend:

  • [base] = Julia Base / stdlib (no install needed)
  • [extra] = Needs installation (Pkg.add("..."))

2. Getting Started with Julia

Install Julia (Recommended): Use Juliaup for easy installation and version management (like pyenv or conda for Python).

  • On Windows: install from the Microsoft Store.
  • On macOS/Linux: run curl -fsSL https://install.julialang.org | sh in your terminal.
  • See juliaup documentation for details.

Alternative: Download binaries from julialang.org/downloads

Start the REPL: Open a terminal and run julia.

Run a script: julia myscript.jl

Install a package:

  1. Enter package mode: type ] in the REPL
  2. Add a package: add DataFrames
  3. Back to Julia: press Backspace or Ctrl+C

Get help: Type ? in the REPL, then a function name (e.g., ?mean).

Hello World Plot:

using CairoMakie
scatter(1:5, rand(5))

(Install with ] add CairoMakie if needed)


3. Achieving Reproducibility in Julia

Reproducibility is essential for scientific computing. Julia makes it easy to create reproducible environments and results.

  • Use project environments:
    • In your project folder, run julia and then ] activate . to create/use a local environment.
    • Add packages with ] add PackageName.
    • This creates Project.toml and Manifest.toml files, which record exact package versions.
    • Share these files to let others exactly reproduce your environment: ] instantiate installs all dependencies.
  • Set random seeds:
    • For reproducible random numbers, set a seed: using Random; Random.seed!(1234)
  • Save scripts and notebooks:
    • Keep your code, data, and environment files together for full reproducibility.

See the Pkg documentation for more details on environments and reproducibility.


4. Top 5 Performance Tips (Quick Reference)

  1. Write code inside functions, not at global scope
  2. Use concrete types for arrays and variables
  3. Prefer broadcasting (.) for elementwise operations
  4. Pre-allocate arrays outside loops
  5. Profile and benchmark with @profile and @btime

5. Common Pitfalls & Tips

Pitfall / TipJuliaPythonNote
IndexingA[1] (1-based)A[0] (0-based)Julia starts at 1!
Assignment vs. equality= vs. === vs. ==Same as Python
Broadcastingsin.(A)np.sin(A)Use . for elementwise
Mutate arraypush!(a, x)a.append(x)! = mutates
SlicingA[2:4] (includes 4)A[1:4] (excludes 4)Inclusive in Julia
Type stabilityUse concrete typesDynamicFor speed
Package manager] add ...pip install ...Use REPL pkg mode
Function definitionf(x) = x^2def f(x): return x**2Short syntax
String interpolation"x = $x"f"x = {x}"Dollar sign
Comments#, #= =##, ''' '''Multi-line

6. REPL & Package Manager Shortcuts

ShortcutAction
]Enter package manager
?Help mode
;Shell mode
TabAutocomplete
Ctrl+CInterrupt execution
; in pkg modeRun shell command

7. Migration Quick Wins (Python/MATLAB/IDL → Julia)

Quick wins and idioms for users migrating from Python, MATLAB, or IDL:

Python → Julia

MATLAB → Julia

MATLABJuliaNotes
A = zeros(3,4)A = zeros(3,4)Same
A(:,2)A[:,2]1-based
A(2,3)A[2,3]Brackets
length(A)length(A)Same
mean(A)mean(A)Same
A.*BA .* BSame
A.^2A .^ 2Same
plot(x,y)plot(x,y)PyPlot/Makie
for i=1:10for i in 1:10end closes block
function f(x)f(x) = ...Short syntax

IDL → Julia

IDLJuliaNotes
a = findgen(10)a = collect(0:9)0-based in IDL
where(a GT 0)findall(>(0), a)Boolean indexing
mean(a)mean(a)Same
plot, x, yplot(x, y)PyPlot/Makie
for i=0,9 do ... endforfor i in 1:10 ... end1-based

Finding Packages & Getting Help

  • Search for packages: juliahub.com or pkg.julialang.org
  • Read error messages from the bottom up for the root cause.
  • Use ] activate . in your project folder for local environments.
  • Use Project.toml and Manifest.toml for reproducibility.
  • For Python: using PythonCall; pyimport("numpy") | For R: using RCall; R"..."
  • Save/load data with JLD2, HDF5, CSV (not the whole workspace).
  • Community: Julia Discourse, Slack, Zulip, StackOverflow, GitHub.

I. Essential Packages & Ecosystem

Julia's package ecosystem is designed for scientific and technical computing. This section lists the most important packages, grouped by domain. Packages marked [base] are included with Julia; [extra] require installation.

Core \& Data Packages

PackagePurpose/DomainBase?Key Functions
LinearAlgebraDense/sparse matrix ops[base]det, inv, eigen, svd, norm
StatisticsBasic statistics[base]mean, std, var, cor, cov
RandomRandom numbers[base]rand, randn, shuffle
PrintfC-like formatting[base]@printf, @sprintf
DatesDate/time handling[base]Date, DateTime, now, today
ProfileCode profiler[base]@profile, Profile.clear()
DelimitedFilesDelimited text I/O[base]readdlm, writedlm
DataFramesTabular data, analysis[extra]DataFrame, select, filter, groupby
CSVCSV file I/O[extra]CSV.read, CSV.write
MeasurementsError propagation[extra]±, measurement, value, uncertainty
Unitful, UnitfulAstroUnits (SI, astro)[extra]u"m", u"pc", uconvert
AstroLibAstronomical utilities[extra]radec2gal, helio_jd, planck
SpecialFunctionsΓ, ζ, Bessel, Airy, etc.[extra]gamma, beta, erf, besselj
DistributionsStatistical distributions[extra]Normal, Poisson, fit, rand
FFTWFast Fourier transform[extra]fft, ifft, plan_fft
RootsFind roots/zeros[extra]find_zero, fzero
DifferentialEquationsODEs, PDEs, SDEs, DDEs[extra]ODEProblem, solve, CallbackSet
HypothesisTestsStatistical tests[extra]OneSampleTTest, KSTest
StatsBaseExtended statistics[extra]fit, Histogram, ecdf, sample
StatsModels, GLMStatistical modeling[extra]lm, glm, @formula
LsqFitCurve fitting[extra]curve_fit, @.
Optim, NLoptOptimization[extra]optimize, BFGS, NelderMead
MLJ, Flux, KnetMachine learning[extra]machine, Chain, Dense
ProgressMeterProgress bars[extra]@showprogress, Progress
BenchmarkToolsAccurate benchmarking[extra]@benchmark, @btime
ReviseLive code reloading[extra]Auto-reload on file change
DebuggerDebugging[extra]@enter, @run, @bp

File Formats \& I/O Packages

PackageFormatKey Functions
JLD2Julia native binary@save, @load, jldopen
HDF5HDF5 scientific datah5open, h5read, h5write
MATMATLAB .mat filesmatread, matwrite
FITSIOFITS (astronomy)FITS, read, write
NetCDFNetCDF scientificNetCDF.open, ncread, ncwrite
NPZNumPy .npy/.npznpzread, npzwrite
NpyNumPy .npy (mmap)NpyArray, npyread, npywrite

Language Interoperability

PackageInterop WithKey Functions
PythonCallPython (modern)pyimport, @py, Py
PyCallPython@pyimport, py"...", pyeval
RCallRR"...", @rget, @rput
CxxWrapC++Wrap C++ code
JavaCallJavaCall Java methods
ccallC/Fortranccall((:func, "lib"), RetType, (ArgTypes,), args...)

Plotting \& Visualization

PackageBackendKey Functions
CairoMakie2D publicationFigure, Axis, lines!, scatter!
GLMakie3D interactiveactivate!, meshscatter!, surface!
WGLMakieWeb/browserWeb-based interactive plots
PyPlotMatplotlibplot, scatter, hist, xlabel

Development \& Interactive

PackagePurposeKey Functions
IJuliaJupyter notebooks, JupyterLabnotebook(), JupyterLab, Jupyter integration
PlutoReactive notebooksPluto.run(), reactive environment
QuartoScientific/technical docs, notebooks.qmd files, multi-language, Jupyter/Pluto support
WeaveLiterate programmingweave("file.jmd"), markdown+code
ProfileViewProfile visualization@profview, visual profiler

Editors & IDEs for Julia

Editor/IDETypeNotes
VS CodeIDEJulia extension, debugging, plotting
Juno (Atom)IDEDiscontinued, but still used
Vim/NeovimEditorJulia syntax, plugins available
EmacsEditorjulia-mode, lsp-julia
Sublime TextEditorJulia syntax support
JupyterLabNotebook/IDEWith IJulia kernel
PlutoNotebookReactive, browser-based
QuartoNotebook/docsMulti-language, Julia support
WeaveLiterate programmingMarkdown+code, report generation

IIa. Control Flow & Loops

Julia's control flow is similar to Python, but uses end to close blocks. For best performance with arrays, use vectorized/broadcasted operations or type-stable, pre-allocated loops.

Conditionals

if x > 0
    println("positive")
elseif x < 0
    println("negative")
else
    println("zero")
end

For Loops

for i in 1:10
    println(i)
end

# Loop over arrays
for x in arr
    println(x)
end

While Loops

i = 1
while i <= 10
    println(i)
    i += 1
end

square_all!(y, x)

Performance Tips for Loops

  • Prefer vectorized or broadcasted operations: y = sin.(x)
  • For custom loops, pre-allocate output arrays: result = similar(x)
  • Use concrete types and avoid changing array types inside loops
  • Use @inbounds to skip bounds checking (safe if you know indices are valid)
  • Avoid global variables in loops; wrap code in functions for speed

Example (fast, 1D):

function square_all!(y, x)
    @inbounds for i in eachindex(x)
        y[i] = x[i]^2
    end
end
y = similar(x)
square_all!(y, x)

Nested Loops for Multi-Dimensional Arrays (Performance)

For best performance with multi-dimensional arrays, use nested loops with @inbounds and access elements in column-major order (first index fastest in Julia). This avoids temporary allocations and leverages Julia's memory layout.

Example (2D array, fill with sum of indices):

function fill_sum!(A)
    @inbounds for j in axes(A,2)   # columns outer
        for i in axes(A,1)         # rows inner (fastest)
            A[i,j] = i + j
        end
    end
end
A = zeros(1000,1000)
fill_sum!(A)

Why: Julia stores arrays in column-major order (like Fortran/MATLAB), so looping with the first index innermost is cache-friendly and fastest.


General Performance Tips:

  • Write code inside functions, not at global scope (Functions are much faster than global code in Julia)
  • Use concrete types for arrays and variables (E.g., Vector{Float64} not Vector{Any}; concrete types allow Julia to generate fast code)
  • Avoid type changes in variables (type instability) (Don't assign different types to the same variable; e.g., keep x always a Float64)
  • Use @btime from BenchmarkTools for timing (Accurate benchmarking, better than @time)
  • Prefer eachindex(A) for array iteration (eachindex(A) gives the most efficient and safe way to loop over all indices of A, even for non-contiguous arrays)
  • Use broadcasting (.) for elementwise ops (E.g., sin.(x) applies sin to every element of x)
  • Avoid unnecessary memory allocations (Pre-allocate arrays outside loops; don't create new arrays in every iteration)
  • Use @inbounds and @views for advanced speedups (@inbounds skips bounds checking; @views avoids copying slices)
  • Profile with @profile and visualize with ProfileView (Find bottlenecks in your code)

II. Arrays, Math, Stats & Data Operations

Julia's array and math syntax is similar to MATLAB and Python (NumPy), but with 1-based indexing! This section covers array creation, indexing, math, statistics, and data operations. See notes for common pitfalls.

Arrays and Indexing (1-based!)

Note: Julia arrays are 1-based (first element is at index 1, not 0). Slicing is inclusive. Broadcasting uses the dot (.) syntax.

TaskJulia CodeNotes
Row vector, col vector[1 2 3], [1; 2; 3]2D shapes (1,3), (3,1)
1D vector, matrix[1, 2, 3], [1 2; 3 4]
Zeros, ones, identityzeros(2,2), ones(2,2), I
Range, linspace, logspace1:2:9, range(0,1,length=10), exp10.(range(log10(1), log10(100), length=5))
Reshape, flattenreshape(A, 3,4), vec(A)
Indexing/slicingA[2:4, 1:2], A[end, 1:end-1]Inclusive ranges
Boolean indexingA[A .> 0]Broadcast comparison

Linear Algebra & Math

Julia's LinearAlgebra standard library provides efficient matrix and vector operations. Use using LinearAlgebra to access advanced features.

TaskJulia CodePackage
Matrix multiplyA * B[base]
Elemwise multiplyA .* B[base]
Dot productdot(a, b), a ⋅ bLinearAlgebra
Norm, inv, detnorm(A), inv(A), det(A)LinearAlgebra
Eigenvaluesvals, vecs = eigen(A)LinearAlgebra
SVDU, S, V = svd(A)LinearAlgebra
Choleskycholesky(A)LinearAlgebra
QR factorizationQ, R = qr(A)LinearAlgebra
Solve Ax = bA \ b[base]
FFTfft(x), ifft(X)FFTW

Statistics & Distributions

Julia's Statistics and Distributions packages provide a rich set of statistical tools. Use using Statistics, Distributions to access these functions.

TaskJulia CodePackage
Basic statsmean(x), std(x), var(x)Statistics
Quantilesquantile(x, [0.25,0.5,0.75])Statistics
Correlation/covariancecor(x, y), cov(x, y)Statistics
Histogramfit(Histogram, x, nbins=10)StatsBase
ECDFecdf(x)StatsBase
Statistical testsOneSampleTTest(x), KSTest(x,y)HypothesisTests
Fit distributionsfit(Normal, x), fit(Gamma, x)Distributions
Sample from distributionrand(Normal(0,1), 100)Distributions
Curve fitting (nonlinear)@. model(x, p) = p[1]*exp(-p[2]*x)<br>fit = curve_fit(model, xdata, ydata, p0)LsqFit
Linear regressionfit(LinearModel, @formula(y ~ x), df)GLM
Polynomial fitpolyfit(x, y, deg)Polynomials
Robust fitfit(LinearModel, @formula(y ~ x), df, contrasts=Dict(:x=>DummyCoding()))GLM
Spline fitSpline1D(x, y)Dierckx
Quantile regressionfit(QuantRegModel, @formula(y ~ x), df)QuantileReg

Units, Measurements & Astronomy

Julia supports physical units, error propagation, and astronomy-specific calculations via dedicated packages. Use using Unitful, Measurements, AstroLib as needed.

TaskJulia CodePackage
Attach unitsv = 10u"km/s"Unitful
Astronomical unitsd = 1u"pc", t = 1u"yr"UnitfulAstro
Unit conversionuconvert(u"m/s", v)Unitful
Measurement with errora = 3.1 ± 0.2Measurements
Error propagationc = a + b; d = a*bMeasurements
Coordinate conversionradec2gal(ra, dec)AstroLib
Julian datejdcnv(year, month, day)AstroLib

DataFrames & CSV Operations

For tabular data, use DataFrames.jl (like pandas in Python). For CSV I/O, use CSV.jl. Always check for missing data and column types.

TaskJulia ExamplePackage
Create DataFramedf = DataFrame(x=[1,2,3], y=["a","b","c"])DataFrames
Load/save CSVCSV.read("file.csv", DataFrame)<br>CSV.write("out.csv", df)CSV
Quick viewfirst(df, 5), describe(df)DataFrames
Filter rowsfilter(row -> row.x > 1, df)DataFrames
Select columnsselect(df, :x, :y)DataFrames
Group + aggregatecombine(groupby(df, :group), :value => mean)DataFrames
Join tablesinnerjoin(df1, df2, on=:id)DataFrames

IVa. Multiple Dispatch, Functional & Object-Oriented Programming

Julia is built around multiple dispatch and functional programming, with minimal object orientation. This enables flexible, high-performance code.

Multiple Dispatch (Core Paradigm)

Functions can have many methods, chosen by argument types. This is more general than single-dispatch OOP.

# Example: area for different shapes
area(r::Real) = π * r^2              # Circle
area(w::Real, h::Real) = w * h       # Rectangle
struct Triangle; base; height; end
area(t::Triangle) = 0.5 * t.base * t.height

area(2.0)                # Circle
area(3.0, 4.0)           # Rectangle
area(Triangle(3, 4))     # Triangle

Functional Programming

Functions are first-class: pass them as arguments, return them, use anonymous functions.

map(sin, 0:0.1:π)                # Apply sin to each element
filter(isodd, 1:10)               # Keep only odd numbers
reduce(+, 1:100)                  # Sum all numbers
f = x -> x^2 + 1                  # Anonymous function
g(x) = x^2 + 1                    # Named function

Minimal Object Orientation

Julia uses structs for data, but methods are defined outside structs (no classes). Inheritance is limited to abstract types.

abstract type Shape end
struct Circle <: Shape; r; end
struct Rectangle <: Shape; w; h; end
area(s::Shape) = error("not implemented")
area(c::Circle) = π * c.r^2
area(r::Rectangle) = r.w * r.h

shapes = [Circle(1), Rectangle(2,3)]
areas = area.(shapes)   # Broadcasting over array of shapes

Note: There is no method overloading by object (no obj.method()), but you can use do blocks and closures for encapsulation.


III. Visualization & Plotting

Julia offers several plotting libraries. Makie.jl is modern and flexible; PyPlot provides a matplotlib-like interface. Choose the backend that fits your needs.

Makie.jl Backends (Comprehensive Plotting)

BackendUse CaseActivation
CairoMakiePublication 2D plotsusing CairoMakie; activate!()
GLMakieInteractive 3D plotsusing GLMakie; activate!()
WGLMakieWeb-based plotsusing WGLMakie; activate!()

Common Plotting Examples

# Makie basic plotting
using CairoMakie
fig = Figure()
ax = Axis(fig[1, 1], xlabel="x", ylabel="y")
lines!(ax, 1:10, rand(10))
scatter!(ax, 1:10, rand(10))
fig

# 3D with GLMakie
using GLMakie
x = y = -10:0.5:10
z = [sin(sqrt(i^2 + j^2)) for i in x, j in y]
surface(x, y, z)

# PyPlot (matplotlib style)
using PyPlot
plot(1:10, rand(10))
scatter(1:5, rand(5))
xlabel("x"); ylabel("y")




IVb. Metaprogramming

Julia supports powerful metaprogramming: you can generate, inspect, and transform code at runtime using macros and expressions. This enables advanced code reuse, domain-specific languages, and performance optimizations.

Macros and Expressions

Macros operate on code before it runs. Use @macro to transform code, and :expr to represent code as data.

# Example: @show macro prints code and value
@show 2 + 2
# Output: 2 + 2 = 4

# Build and evaluate expressions
ex = :(a + b^2)
eval(ex)   # Evaluates the expression in global scope

# Define your own macro
macro sayhello(name)
    :(println("Hello, $name!"))
end
@sayhello "Julia"

Advantages:

  • Write code that writes code (DRY principle)
  • Create custom control structures and DSLs
  • Enable compile-time checks and optimizations
  • Used for performance tools (e.g., @btime, @inbounds, @views)

IV. Scientific Programming & Performance

Julia's multiple dispatch, macros, and performance tools enable high-performance scientific code. This section covers idiomatic Julia programming and optimization.

Functions & Multiple Dispatch

Multiple dispatch is Julia's core paradigm: functions can have different methods for different argument types. Use broadcasting (.) to apply functions elementwise.

# Short function syntax
f(x) = x^2

# Multiple dispatch
area(r::Real) = π * r^2                    # Circle
area(w::Real, h::Real) = w * h             # Rectangle
area(triangle::Triangle) = 0.5 * triangle.base * triangle.height

# Broadcasting
sin.(x)                                    # Apply sin to each element
my_function.(array)                        # Works with any function

Performance Tools

Use these tools to benchmark, profile, and optimize your Julia code. Start with @btime for quick timing, and use @profile for deeper analysis.

TaskJulia CodePackage
Precise timing@btime func(x)BenchmarkTools
Profile code@profile func(x)<br>ProfileView.@profview func(x)[base]/ProfileView
Progress bar@showprogress for i in 1:N ... endProgressMeter
Live reloadusing Revise (auto-reload files)Revise

Parallelism & GPU

Julia supports multithreading, distributed computing, and GPU acceleration. Use the appropriate macros and packages for your hardware.

TaskJulia CodePackage
MultithreadingThreads.@threads for i in 1:N ... end[base]
Distributed for@distributed for i in 1:N ... endDistributed
Parallel mappmap(f, xs)Distributed
Shared arraysSharedArray{T}(dims)SharedArrays
MPI (cluster)using MPI; MPI.Init(); ...MPI.jl
Task-based DAG@spawnat, @async, @sync[base]
Dagger DAGusing Dagger; delayed(f)(args...)Dagger.jl
GPU arraysusing CUDA; x = CuArray(rand(1000))CUDA
Multi-GPUCUDA.devices(), CUDA.@syncCUDA
ThreadsXThreadsX.map(f, xs)ThreadsX
FLoops@floop for ... endFLoops


V. Language Interoperability & File I/O

Julia can call C, Fortran, Python, R, and more. It also supports many scientific file formats. This section summarizes the main interop and I/O options.

Calling Other Languages

Call C/Fortran directly with ccall, or use packages for Python, R, and C++. For details, see the official Julia documentation.

LanguageMethodExample
Fortranccall with mangled namesccall((:__module_MOD_func, "lib.so"), Float64, (Ref{Float64},), x)
Cccall directccall((:cos, "libm"), Float64, (Float64,), x)
PythonPythonCall.jl (modern)py = pyimport("numpy"); py.array([^1][^2][^3])
RRCall.jlR"mean(c(1,2,3))"
C++CxxWrap.jlWrap C++ classes/functions

Calling Julia FROM Other Languages

Julia can be embedded in Python, R, C/C++, or called as a compiled executable. See the relevant package docs for setup.

LanguageMethodReference
PythonPythonCall.jl (bidirectional)Use JuliaCall from Python side
RJuliaCall packagelibrary(JuliaCall); julia_setup()
C/C++Embed libjuliaUse julia.h, call jl_init()
ExecutablePackageCompiler.jlcreate_app(src, dest)
Binary executablePackageCompiler.jlcreate_executable("file.jl", "myprog")
From FortranC interfaceCall jl_init(), jl_eval_string() from Fortran via C interoperability

File Format Examples

Common scientific file formats are supported via dedicated packages. Always check read/write options and data types.

FormatWrite ExampleRead Example
JLD2@save "data.jld2" x y z@load "data.jld2" x y z
HDF5h5write("file.h5", "dataset", array)data = h5read("file.h5", "dataset")
NPYnpzwrite("data.npy", array)array = npzread("data.npy")
MATmatwrite("data.mat", Dict("A"=>A))vars = matread("data.mat")
FITSFITS("img.fits", "w") do f; write(f, data); endf = FITS("img.fits"); data = read(f[^1])
CSVCSV.write("data.csv", df)df = CSV.read("data.csv", DataFrame)


VI. Migration Tips: Python → Julia

Key differences: Julia uses 1-based indexing, inclusive slicing, and multiple dispatch. Broadcasting is explicit with .. See table for common mappings.

Key Syntax Differences

ConceptPythonJuliaNotes
IndexingA (0-based)A[^1] (1-based)Major difference!
SlicingA[1:3] (excludes 3)A[2:3] (includes 3)Inclusive in Julia
Broadcastingnp.sin(A) (ufuncs)sin.(A) (universal)Dot works on all functions
PowerA**2A.^2 (elementwise)^ is matrix power
String interpf"x = {x}""x = $x"Dollar sign syntax
Boolean opsand, or, not&&, `
Comments# single, """multi"""# single, #= multi =#

Performance \& Ecosystem

  • Speed: Julia often 10-100x faster for numerical code without optimization
  • Compilation: First run slower (JIT), subsequent runs fast
  • Type system: Optional but helpful for performance
  • Multiple dispatch: Natural in Julia, not available in Python
  • Package maturity: Python has broader ecosystem, Julia growing rapidly
  • Scientific focus: Julia designed for scientific computing from ground up

Common Function Mappings

Python (NumPy)JuliaPackage
np.array([^1][^2][^3])[^1][^2][^3][base]
np.zeros((2,3))zeros(2, 3)[base]
np.linspace(0,1,10)range(0, 1, length=10)[base]
np.random.randn(100)randn(100)Random
np.mean(x)mean(x)Statistics
np.linalg.solve(A,b)A \ b[base]
scipy.optimize.minimizeoptimize(f, x0)Optim
pd.DataFrame()DataFrame()DataFrames
plt.plot(x, y)plot(x, y)PyPlot/Makie


VII. Essential One-Liners & Common Patterns

Handy Julia idioms for scientific computing. Try these in the REPL or a notebook.

# Create and manipulate arrays
A = rand(3, 3)                           # 3×3 random matrix
B = A .+ 1                               # Add 1 to each element
C = A * B                                # Matrix multiplication
x = A \ rand(3)                          # Solve linear system

# Statistics and fitting
data = randn(1000)                       # 1000 random samples
μ = mean(data)                           # Sample mean
dist = fit(Normal, data)                 # Fit normal distribution
samples = rand(dist, 100)                # Generate new samples

# Units and measurements
d = 10u"km"                              # Distance with units  
t = 2u"hr"                               # Time with units
v = d/t                                  # Velocity (automatic units)
measurement = 5.0 ± 0.1                  # Value with uncertainty

# File I/O
@save "results.jld2" A B x               # Save multiple variables
@load "results.jld2" A B x               # Load them back
df = CSV.read("data.csv", DataFrame)     # Read CSV file

# Plotting
using CairoMakie
scatter(1:10, rand(10))                  # Quick scatter plot
lines!(1:10, sin.(1:10))                 # Add line to same plot

# Performance and profiling
@btime sort(rand(1000))                  # Benchmark operation
@showprogress for i in 1:10^6 end       # Progress bar


VIII. Resources & Further Learning

Explore the Julia ecosystem and community. Use ?func in the REPL for help on any function.

Quick Help Commands

  • ?func - Get help for function
  • names(Module) - List exported names
  • methods(func) - Show all methods
  • @which func(args) - Show which method is called
  • typeof(x) - Show type of variable