# Basic variable declaration
= 1 # Implicit typing
x ::Int64 = 5 # Explicit type annotation
y
# Common types
= 42 # Integer
num_int = 19.99 # Float
num_float = true # Boolean
is_student = "Julia" # String
name
# Check type
typeof(num_int) # Returns Int64
typeof(num_float) # Returns Float64
Julia Syntax Cheatsheet
Applied Optimization with Julia
Variables and Basic Types
Variable Declaration and Types
String Interpolation
= "Julia"
name = 30
age # Basic interpolation
= "I am $age years old"
message # Complex interpolation
= "Hello, my name is $name and I am $age years old" greeting
Type Conversion
# Convert between types
= Float64(42) # Int to Float
float_num = Int64(3.14) # Float to Int
int_num = string(42) # Number to String str_num
Key Points
- Variables are dynamic, types are not
- Use
typeof()
to check variable type - String interpolation is powerful for formatted output
Vectors, Matrices, and Tuples
Vectors
# Create vectors
= [95, 87, 91, 78, 88] # Numeric vector
grades = ["Mike", "Yola", "Elio"] # String vector
names
# Vector operations
push!(grades, 82) # Add element to end
pop!(grades) # Remove last element
popfirst!(grades) # Remove first element
# Vector indexing
= grades[1] # Access first element
first = grades[1:3] # Access first three elements subset
Matrices
# Create matrices
= [1 2 3; 4 5 6] # 2x3 matrix
matrix # Matrix operations
2,3] = 17 # Change specific element
matrix[
# Matrix arithmetic
= [2 2; 3 3]
matrix1 = [1 2; 3 4]
matrix2 = matrix1 + matrix2 # Matrix addition
sum_matrix = matrix1 * matrix2 # Matrix multiplication
prod_matrix = matrix1 .* matrix2 # Element-wise multiplication
element_prod
# Broadcasting
.+ 10 # Add 10 to each element matrix
Tuples
# Create tuples (immutable)
= ("Elio Smith", 18, "Hamburg")
person = (255, 0, 0)
rgb
# Tuple operations
= person[1] # Access first element
name = person[2:3] # Multiple assignment age, city
Key Differences
- Vectors: Mutable, 1-dimensional, good for lists
- Matrices: Mutable, 2-dimensional, good for linear algebra
- Tuples: Immutable, fixed-size, good for grouping related constants
Comparison and Logical Operators
Basic Comparisons
# Comparison operators
== y # Equal to
x != y # Not equal to
x < y # Less than
x > y # Greater than
x <= y # Less than or equal to
x >= y # Greater than or equal to
x
# Examples
= (input == "secret123")
password_correct = (age >= 18)
is_adult = (price <= budget) can_afford
Logical Operators
# AND operator (&&)
= (age >= 18) && (money >= price) # Both conditions must be true
can_buy
# OR operator (||)
= (temp < 10) || is_raining # At least one must be true
need_coat
# NOT operator (!)
= !is_open # Inverts boolean value is_closed
Chained Comparisons
# Instead of
>= 0 && x <= 10 # Check if x is between 0 and 10
x
# You can write
0 <= x <= 10 # More natural syntax
# Real-world examples
= 36.5 <= body_temp <= 37.5
normal_temp = 9 <= current_hour < 17 work_hours
Key Points
- Comparisons return boolean values (
true
orfalse
) &&
requires all conditions to be true||
requires at least one condition to be true!
inverts a boolean value- Chained comparisons make range checks more readable
Loops and Iterations
For Loops
# Basic for loop with range
for i in 1:3
println(i) # Prints 1, 2, 3
end
# Iterating over array
= ["apple", "banana", "cherry"]
fruits for fruit in fruits
println(fruit) # Prints each fruit
end
# For loop with break
for x in 1:10
if x == 4
break # Exits loop when x is 4
end
end
# For loop with conditions
for x in 1:10
if x <= 2
println(x)
elseif x == 3
println("Three!")
else
break
end
end
While Loops
# Basic while loop
= 10
number while number >= 5
-= 1 # Decrements until < 5
number end
# Infinite loop with break
= 0
current while true
+= 1
current if current == 5
break # Exits when condition met
end
end
# While loop with condition
= 3
lives while lives > 0
-= 1 # Continues until lives = 0
lives end
Nested Loops
# Nested loop example
= ["S", "M", "L"]
sizes = ["Red", "Blue"]
colors for size in sizes
for color in colors
println("$color $size")
end
end
# Matrix iteration
for i in 1:3
for j in 1:2
println("Position: $i,$j")
end
end
List Comprehensions
# Basic list comprehension
= [n^2 for n in 1:5] # [1,4,9,16,25]
squares
# With condition
= [n for n in 1:10 if n % 2 == 0] # [2,4,6,8,10]
evens
# Nested comprehension
= [i*j for i in 1:3, j in 1:3] # 3x3 multiplication table matrix
Key Points
for
loops are best when you know the number of iterationswhile
loops are useful for unknown iteration counts- Use
break
to exit loops early - List comprehensions offer concise array creation
- Nested loops are useful for multi-dimensional iteration
Dictionaries
Basic Dictionary Operations
# Create a dictionary
= Dict(
student_ids "Elio" => 1001,
"Bob" => 1002,
"Yola" => 1003
)
# Access values
= student_ids["Elio"] # Get value by key
id "David"] = 1004 # Add new key-value pair
student_ids[delete!(student_ids, "Bob") # Remove entry
# Check key existence
if haskey(student_ids, "Eve")
println(student_ids["Eve"])
end
Advanced Operations
# Dictionary with array values
= Dict(
grades "Elio" => [85, 92, 78],
"Bob" => [76, 88, 94]
)
# Get all keys and values
= keys(grades) # Get all keys
names = values(grades) # Get all values
scores
# Iterate over dictionary
for (student, grade_list) in grades
= sum(grade_list) / length(grade_list)
avg println("$student: $avg")
end
Common Methods
# Dictionary methods
length(dict) # Number of entries
empty!(dict) # Remove all entries
get(dict, key, default)# Get value or default if key missing
merge(dict1, dict2) # Combine two dictionaries
copy(dict) # Create shallow copy
Key Points
- Keys must be unique
- Values can be of any type (including arrays)
- Use
haskey()
to safely check for key existence - Dictionaries are mutable (can be changed)
- Keys are accessed with square brackets
dict["key"]
Functions
Basic Function Definition
# Basic function with explicit return
function say_hello(name)
return "Hello, $(name)!"
end
# Function with implicit return
function multiply(a, b)
* b # Last expression is automatically returned
a end
# Conditional return
function do_something(a, b)
if a > b
return a * b
else
return a + b
end
end
Function Scope
# Local scope example
function bake_cake()
= "vanilla" # Only exists inside function
secret_ingredient return secret_ingredient # Must return to access outside
end
# Variables outside function not accessible inside
= 10
global_var function scope_example()
# Can read global_var but can't modify it
return global_var + 5
end
Multiple Dispatch
# Generic operation for all types
function operation(a, b)
"Generic operation for $(typeof(a)) and $(typeof(b))"
end
# Type-specific implementations
operation(a::Number, b::Number) = a + b # For numbers
operation(a::String, b::String) = string(a, b) # For strings
# Usage examples
operation(10, 20) # Returns 30
operation("Hello", "!") # Returns "Hello!"
operation("Hi", 42) # Uses generic operation
Key Points
- Functions can have explicit or implicit returns
- Last expression is automatically returned if no
return
statement - Variables inside functions are local by default
- Multiple dispatch allows different behavior based on argument types
- Use
return
for early exits or conditional
Package Management
Basic Package Operations
# Import package manager
import Pkg # Access as Pkg.function()
using Pkg # Import all exported names
# Add packages
Pkg.add("DataFrames") # Add single package
Pkg.add(["Package1", "Package2"]) # Add multiple packages
# Update packages
Pkg.update() # Update all packages
Pkg.update("DataFrames") # Update specific package
# Remove packages
Pkg.rm("DataFrames") # Remove package
Package Usage
# Import packages
import DataFrames # Access as DataFrames.function()
using DataFrames # Import all exported names
# Check installed packages
Pkg.status() # List all installed packages
Environment Management
# Environment operations
Pkg.activate("new_environment") # Create/activate environment
Pkg.activate() # Activate default environment
# Project files
# Project.toml - Lists direct dependencies
# Manifest.toml - Complete dependency graph
Key Points
- Use
import
for namespace control,using
for direct access - Always update packages regularly with
Pkg.update()
- Create separate environments for different projects
- Project.toml and Manifest.toml track dependencies
- Package manager commands typically run in REPL
DataFrames
Creating DataFrames
using DataFrames
# Basic DataFrame creation
= DataFrame(
df = ["John", "Mike", "Frank"],
Name = [28, 23, 37],
Age = [50000, 62000, 90000]
Salary
)
# Empty DataFrame with specified columns
= DataFrame(
df_empty = String[],
Name = Int[]
Age )
Accessing and Modifying Data
# Access columns
= df.Age # Get Age column
ages = df.Name[1] # First name in Name column
first_name
# Modify values
1] = 59000 # Update John's salary
df.Salary[= zeros(3) # Add new column
df.NewColumn
# Access multiple columns
= df[:, [:Name, :Age]] # Select specific columns
subset = df[1, :] # Select first row row
Filtering Data
# Filter with boolean indexing
= df[df.Salary .> 60000, :]
high_earners
# Using filter function
= filter(row -> row.Salary > 60000, df)
high_earners
# Multiple conditions
= df[(df.Age .> 30) .& (df.Salary .> 60000), :] senior_high_earners
Data Manipulation
# Sort DataFrame
= sort(df, :Age) # Sort by Age
sorted_df = sort(df, [:Age, :Salary]) # Sort by multiple columns
sorted_df
# Add calculated column
= [row.Age > 30 ? row.Salary * 0.1 : row.Salary * 0.05 for row in eachrow(df)]
df.Bonus
# Iterate over rows
for row in eachrow(df)
println("$(row.Name): $(row.Age) years old")
end
Key Functions
nrow(df) # Number of rows
ncol(df) # Number of columns
names(df) # Column names
describe(df) # Summary statistics
push!(df, row) # Add new row
select(df, :Name) # Select columns
Key Points
- Column access with dot notation (df.column)
- Use eachrow() for row iteration
- Boolean indexing for filtering
- push! to add new rows
- Broadcasting with dot operators (.>, .+, etc.)
File Input/Output
DelimitedFiles Operations
using DelimitedFiles
# Write matrix to CSV
= [1 2 3; 4 5 6]
data writedlm("data.csv", data, ',') # Write with comma delimiter
writedlm("data.txt", data, '\t') # Write with tab delimiter
# Read delimited files
= readdlm("data.csv", ',') # Read CSV file
matrix = readdlm("data.txt", '\t') # Read tab-delimited file matrix
CSV and DataFrame Operations
using CSV, DataFrames
# Write DataFrame to CSV
= DataFrame(
df = ["John", "Alice"],
Name = [25, 30]
Age
)write("data.csv", df) # Basic write
CSV.write("data.csv", df, # Write with options
CSV.= ';', # Custom delimiter
delim = false # No header
header
)
# Read CSV to DataFrame
= CSV.read("data.csv", DataFrame) # Basic read
df = CSV.read("data.csv", DataFrame, # Read with options
df = ';', # Custom delimiter
delim = ["Col1", "Col2"] # Custom headers
header )
File Path Management
# Get current directory
@__DIR__ # Directory of current file
pwd() # Current working directory
# Path operations
= joinpath(@__DIR__, "data") # Join path components
path mkdir(path) # Create directory
isfile(path) # Check if file exists
Key Points
- Use DelimitedFiles for simple matrix I/O
- CSV package for advanced DataFrame I/O
- Always use @__DIR__ for relative paths
- Check file existence before operations
- Consider using try-catch for file operations
Plotting with Plots.jl
Basic Plots
using Plots, StatsPlots
# Line plot
plot(x, y,
="Line Plot",
title="X Label",
xlabel="Y Label",
ylabel=false
legend
)
# Scatter plot
scatter(x, y,
="Scatter Plot",
title=(:circle, 8)
marker
)
# Bar plot
bar(categories, values,
="Bar Plot"
title
)
# Histogram
histogram(data,
=30,
bins="Histogram"
title
)
# Box plot
boxplot(group, values,
="Box Plot"
title )
Plot Customization
# Customize plot appearance
plot(x, y,
="Custom Plot",
title=(:dash, 2), # Line style and width
line=:red, # Line color
color=(:circle, 8), # Marker style and size
marker="Data Series" # Legend label
label
)
# Multiple series
plot(x, y1, label="Series 1")
plot!(x, y2, label="Series 2") # Add to existing plot
Saving Plots
# Save plot to file
savefig(plot_name, "path/plot.png") # Save as PNG
savefig(plot_name, "path/plot.pdf") # Save as PDF
savefig(plot_name, "path/plot.svg") # Save as SVG
Common Options
# Plot options
plot(
=true/false, # Show/hide legend
legend=true/false, # Show/hide grid
grid=(width,height), # Plot dimensions
size=300 # Resolution
dpi
)
# Line styles
:solid, :dash, :dot
# Colors
:red, :blue, :green
# Markers
:circle, :square, :diamond
Key Points
- Use plot() for new plots, plot!() to add to existing
- Customize with named arguments
- Save plots in various formats
- StatsPlots extends plotting capabilities
- Multiple series can share one plot