struct MyRange
start
step
stop
end
function _MyRange(a::MyRange,i::Int)
tmp = a.start + a.step*(i-1)
if tmp > a.stop
error("Index is out of bounds!")
else
return tmp
end
end
a = MyRange(1,2,20)
_MyRange(a,5) == (1:2:20)[5]
Base.getindex(a::MyRange,i::Int) = _MyRange(a,i)
a[5]
struct MyLinSpace
start
stop
n
end
function Base.getindex(a::MyLinSpace,i::Int)
dx = (a.stop-a.start)/a.n
a.start + dx*(i-1)
end
l = MyLinSpace(1,2,50)
l[6]
range(1,stop=2,length=50)[6]
(a::MyRange)(x) = a.start + a.step*(x-1)
a = MyRange(1,2,20)
a(1.1)
using Unitful
a = MyRange(1u"kg",2u"kg",20u"kg")
a[5]
struct StrangMatrix end
A = StrangMatrix()
using LinearAlgebra
function LinearAlgebra.mul!(C,A::StrangMatrix,B::AbstractVector)
for i in 2:length(B)-1
C[i] = B[i-1] - 2B[i] + B[i+1]
end
C[1] = -2B[1] + B[2]
C[end] = B[end-1] - 2B[end]
C
end
Base.:*(A::StrangMatrix,B::AbstractVector) = (C = similar(B); mul!(C,A,B))
A*ones(10)
struct SizedStrangMatrix
size
end
Base.eltype(A::SizedStrangMatrix) = Float64
Base.size(A::SizedStrangMatrix) = A.size
Base.size(A::SizedStrangMatrix,i::Int) = A.size[i]
b = sin.(0:0.1:2π)
A = SizedStrangMatrix((length(b),length(b)))
function LinearAlgebra.mul!(C,A::SizedStrangMatrix,B)
for i in 2:length(B)-1
C[i] = B[i-1] - 2B[i] + B[i+1]
end
C[1] = -2B[1] + B[2]
C[end] = B[end-1] - 2B[end]
C
end
Base.:*(A::SizedStrangMatrix,B::AbstractVector) = (C = similar(B); mul!(C,A,B))
using IterativeSolvers
x = gmres(A,b,tol=1e-14)
A*x - b
#### Prepare Data
X = rand(1000, 3) # feature matrix
a0 = rand(3) # ground truths
y = X * a0 + 0.1 * randn(1000); # generate response
X2 = hcat(X,ones(1000))
println(X2\y)
using MultivariateStats
println(llsq(X,y))
using DataFrames, GLM
data = DataFrame(X1=X[:,1], X2=X[:,2], X3=X[:,3],Y=y)
OLS = lm(@formula(Y ~ X1 + X2 + X3), data)
X = rand(100);
y = 2X + 0.1 * randn(100);
using Plots
b = X\y
println(b)
gr()
scatter(X,y)
Plots.abline!(b[1],0.0, lw=3) # Slope,Intercept
abstract type AbstractPerson end
abstract type AbstractStudent <: AbstractPerson end
struct Person <: AbstractPerson
name
end
struct Student <: AbstractStudent
name
grade
end
struct GraduateStudent <: AbstractStudent
name
grade
end
person_info(p::AbstractPerson) = println(p.name)
person_info(s::AbstractStudent) = (println(s.name); println(s.grade))
person_info(Person("Bob"))
person_info(Student("Bob",2))
person_info(GraduateStudent("Bob",2))
This is from Josh Day's talk: https://www.youtube.com/watch?v=EwcTNzpQ6Sc
Solution is from: https://github.com/joshday/Talks/blob/master/SLG2016_IntroToJulia/Slides.ipynb
using Distributions
function myquantile(d::UnivariateDistribution, q::Number)
θ = mean(d)
tol = Inf
while tol > 1e-5
θold = θ
θ = θ - (cdf(d, θ) - q) / pdf(d, θ)
tol = abs(θold - θ)
end
θ
end
for dist in [Gamma(5, 1), Normal(0, 1), Beta(2, 4)]
@show myquantile(dist, .75)
@show quantile(dist, .75)
println()
end