###### File system navigation ######
# Print the current directory
pwd()
# Change to the parent directory
cd("..")
# Change to C:\ on Windows (notice the forward slash)
cd("C:/")
# List the contents of a directory
readdir()
###### Basic variables and 1D mathematical operations ######
# Make a variable x and assign it the number 2
x = 2
# Same as above, but don't print any output
x = 2;
# Show the contents of the variable x
show(x)
# Show the value of x + 3
x + 3
# Assign the value (x+3) to a variable y
y = x + 3
# Subtract 3 from x in place (this doesn't change y)
x += 4
# Multiplication by constants is really slick
3x
# For multiplying variables
x*x
# Other basic operations
x^2
log(x)
exp(x)
# Rounding to nearest/lower/upper integer
round(x)
floor(x)
ceil(x)
###### Random stuff ######
# Show both the expression and the result of the expression
@show(x + y)
# Run the code contained in a file
include("file.jl")
# Show the documentation for function "include"
?include
# Look for a string among the available functions
apropos("include")
###### Vectors ######
# Make a row vector containing (1,2,3,4)
x = [1 2 3 4]
# Make a column vector containing (1,2,3,4)
x = [1;2;3;4]
# Alternately:
x = [1
2
3
4]
# Number of elements in vector
length(x)
# A vector of 10 zeroes
zeros(10)
# A vector of 10 ones
ones(10)
# A vector of 10 eights
fill(8,10)
# Access element 2 (note that the indexes start at 1, not 0 as in Python and C)
x[2]
# Access first two elements
x[1:2]
# Access last two elements
x[end-1:end]
# Access every second element
x[2:2:end]
# The vector in reverse order
x[end:-1:1]
# x as a column-vector
x[:]
# Scalar multiplication by 3
3x
# Alternately
alpha = 3
alpha*x
# Vector additon
x = [1;2;3]; y = [6,5,4]
x + y
# min, max, argmax, argmin
minimum(x)
maximum(x)
argmax(x)
argmin(x)
# Sum of values in vector
sum(x)
# Product of values in vector
prod(x)
# Square of each element
x.^2
# Exponential and log of each element
exp.(x)
log.(x)
# Sort the elements of the vector
sorted = sort(y)
# Get the indexes needed to sort the vector
sortperm(y)
# Sort the vector in-place
sort!(y)
y
# Inner product of column vectors
x'*y
### CAUTION (vectors and matrices are pointers) ###
# Setting y = x sets y to *point* to the same vector as x
# This is faster than making a copy, but changing x
# also changes y
y = x
x[3] *= 10
y[3] # Will be x[3]*10
y[2] = 0
x[2] # Will be zero
# Changing x on the right-side in any way makes a copy.
y = 1x
x[3] *= 10
y[3] # Will still be the old value of x[3]
y[2] = -1
x[2] # Won't be changed
# Vertical concatenation
x = [2;1] # Defines 2x1 vector [2 1]^T
vcat(x,3) # Returns the 3x1 vector [2 1 3]^T
X = [1 1;2 2;3 3] # Defines a 3x2 matrix
vcat(X,[4 4]) # Returns the 4x2 matrix with [4 4] added as last row
###### Matrices ######
# Create a matrix
A = [1 2 3;4 5 6;7 8 9]
# Alternately
B = [1 2 3
4 5 6
7 8 9]
# Store the dimensions in 'n' and 'd'
(n,d) = size(A)
# Accessing elements
A[2,3]
# Grab the first column
A[:,1]
# Scalar multiplication
2A
# Scalar multplication with variable
alpha*A
# Matrix addition
A + B
# Matrix element-wise multplication
# (this assumes they have the same dimensions)
A.*B
# Matrix multiplication
A*B
# Matrix element-wise power
A.^2
# Matrix-vector multiplication
x = [1;2;3]
A*x
# Make a vector out of the matrix elements, in "column-major" order
A[:]
# Minimum value in the whole matrix
minimum(A)
# Minimum value in each column (returns a row vector)
minimum(A,dims=1)
# Minimum value in each row (returns a column vector)
minimum(A,dims=2)
###### Logic ######
# Boolean variables:
a = true
b = false
# Not operator
!a
# Test equality of scalars
x = 1
y = 1 + 1e-10
x == y
# Test approximate equality
isapprox(x,y)
# Test not equal
x != y
# Apply logical operators element-wise to vectors with '.'
x = [1;2;3]
y = [1;2;4]
x == y # Tests if all elements are equal
x .== y # Tests equality element-wise
# Test if any or all elements of a vector are true
any(x .== y)
all(x .== y)
###### Random Numbers ######
# A random number between 0 and 1
rand()
# A random number between 1 and 10
rand(1:10)
# A vector of 10 random number between 0 and 1
rand(10)
# A vector of 10 samples from a standard normal
randn(10)
###### Control structures ######
### CAUTION (variable scoping in control structures) ###
# Look at the below code carefully,
# to understand why 'i' will be 100 at the end,
# and why we need to write 'global' when updating 't'
# - The for loop creates a new variable 'i' in the loop scope
# - Need to specify 'global' so it doesn't creat a new 't'
i = 100
t = 0
for i in 1:10
global t += 1
end
t # Will be 10
i # Will be 100
# Indenting doesn't matter but makes code look nicer
for i in 1:10
global t += 1
end
# Ugliest version using semi-colons instead of returns (not recommended)
for i in 1:10; global t += 1;end
# While loop
i = 1
while mod(i,10) != 0
global i += 1;
end
# If-else (note that scope works different: 'j' is in outer scope)
if i == 10
j = 10
elseif i == 20
j = 20
else
j = Inf
end
###### Functions ######
# Define a simple one-line one-input one-output function
f(x) = 3(x+2)^2
# Now we can evaluate the function
f(2)
# Using the function name without parentheses gives a pointer to the function
g = f
g(2)
# Multi-input multi-output function
F(x,y) = (2x,x+y)
# Evaluating it and returning multiple arguments
(out1,out2) = F(2,3)
# Multi-line functions use "function" (returns value of last statement)
function f(x)
tau = 2pi;
x + tau;
end
f(10)
# You can also use an explicit "return" for more complicated functions
function f(x,y)
if x >= y
return x # Single output
else
return (x,y) # Multi-output
end
end
f(10,2) # Returns one argument
f(2,10) # Returns two arguments
### CAUTION (pass by value vs. pass by reference) ###
# Julia uses pass by value, so changing argument within function doesn't change the original variable.
# But, if the argument is a pointer (like a vector or matrix) and you change the values in the reference object, they will be changed outside the function too.
# A common convention if a function changes its input is to end the function name with a "!".
function makeBug!(x)
x[2] = -999
end
makeBug!(x) # Changes element 2 to -999 (could be hard to catch when debugging)
# Define a function with named arguments (and default values if missing)
# The ';' means that it's the start of the named arguments
f(x,y;foo=0,bar=1) = (x+foo,y+bar)
# Can be called in various ways (named arguments use defaults if not included)
f(1,2)
f(1,2,foo=1)
f(1,2,bar=1)
f(1,2,foo=1,bar=2)
f(1,2,bar=2,foo=1)
# Apply a function to every row of a matrix A
# (below returns the index of the maximum in each row)
mapslices(argmax, A, dims=2)
##### Some useful Functions located in Packages #####
# Vector Norms
using LinearAlgebra # "Loads" the linear algebra functions
x = [1;2;3]
norm(x)
norm(x,1)
norm(x,Inf)
dot(x,[6;5;4])
I # Identity matrix
# mean, median
using Statistics
mean(x)
median(x)
# printing to screen (useful for debugging)
using Printf
@printf("Hello, World\n")
a = 10
@printf("%d\n", a)
# Read a comma-separated file
using DelimitedFiles
readdlm("data.csv",',')
###### Installing Packages #####
# Installing the package JLD (for saving and loading from Julia data format)
using Pkg # Load the package manager
Pkd.add("JLD") # Install JLD
#### Save and loading data using the JLD Package ######
# Load the package
using JLD
# Save variables X and y in a JLD file
save("file.jld","x",x,"y",y)
# Loading an individual variable
x = load("file.jld","x")
# Loading the variables and their names as a dictionary
data = load("file.jld")
###### Plotting with PyPlot #######
# Run this once to add the package
Pkg.add("PyPlot")
# Run this in each session you want to use the package
using PyPlot
# Basic Line Plot
x = [1;2;3]
y = [4;5;6]
plot(x,y)
# Histogram with 10 bins
x = randn(100)
plt[:hist](x,10)
# Box plot
boxplot(x)
# Scatter plot
scatter(randn(100),randn(100))
### Stack operations
# Add a value to the end of a list
x = [2;1]
push!(x,3) # Changes 'x' in-place to be the 3x1 vector [2;1;3]
# Return the last value in a list, and remove it from the list:
pop!(x) # Returns '3'
###### Comments ######
# For a list of noteworthy differences between Julia and Matlab/R/Python, see here:
# https://docs.julialang.org/en/v1/manual/noteworthy-differences/index.html
# There is a lot more neat stuff like hash functions and regular expressions and list comprehension,
# and lots of neat CS stuff like variable typing for speed and overloading "+".
# I'll try to keep this document up to date with all you need for the assignments.