srand(1234); x = [] # 何でも入るリスト x = Int[] # Int型のみのリスト x = Vector{Int}() # Int[]と同じ x = [1,2,3] # 3要素からなるリスト fill(42, 10) fill("foo", 4) x = [1,2,3] push!(x, 4) # 右に追加 unshift!(x, 0) # 左に追加 append!(x, [5,6,7]) # 別のベクトルを追加 x = [1,2,3,4,5] pop!(x) # 右端を削除 x shift!(x) # 左端を削除 x deleteat!(x, 2) # 特定の場所の要素を削除 issorted([1,2,3,4]) issorted([1,3,2,4]) x = [1,5,4,3,7,6,2] sort(x) # ベクトルを新しく作る sort(x, rev=true) # 逆順でソート sort!(x) # ベクトルを上書きする x = [1,2,3,4] reverse(x) # ベクトルを新しく作る x == [1,2,3,4] reverse!(x) # ベクトルを上書きする x == [1,2,3,4] x = [1,2,3,4,5,6] shuffle(x) # ベクトルを新しく作る x == [1,2,3,4,5,6] shuffle!(x) # ベクトルを上書きする x == [1,2,3,4,5,6] vcat([1,2,3], [4,5,6]) # 縦方向 => ベクトル hcat([1,2,3], [4,5,6]) # 横方向 => 行列 Dict() # 何でも入る空の辞書 Dict{String,Int}() # Stringがキー、Intが値の空の辞書 Dict("one" => 1, "two" => 2) # 初期値のある辞書 haskey(Dict("one" => 1, "two" => 2), "two") haskey(Dict("one" => 1), "two") d = Dict("one" => 1, "two" => 2) d["one"] d["three"] # キーがなければエラー d = Dict("one" => 1, "two" => 2) get(d, "one", 0) # 第三引数がデフォルト値 get(d, "three", 0) d = Dict("one" => 1, "two" => 2) d["three"] = 3 d d = Dict("one" => 1, "two" => 2) keys(d) # イテレータとして取り出す collect(keys(d)) # ベクトルとして取り出す values(d) collect(values(d)) Set{Int}() # 空の集合 Set([1,2,3]) # ベクトルから Set(["foo", "bar", "baz"]) 2 in Set([1,2,3]) 4 in Set([1,2,3]) 2 ∈ Set([1,2,3]) # ∈ は in の別名 s = Set([1,2,3]) push!(s, 4) union!(s, [5, 6]) s1 = Set([1,2,3]) s2 = Set([2,3,4,5]) union(s1, s2) # 和集合 s1 ∪ s2 # \cupは和集合 intersect(s1, s2) # 積集合 s1 ∩ s2 # \capは積集合 setdiff(s1, s2) # 差集合 s = Set([1,2,3]) collect(s) # 順番は順不同 length("foo") length("αβγ") sizeof("foo") sizeof("αβγ") convert(Vector{UInt8}, "foo") convert(Vector{UInt8}, "αβγ") Vector{UInt8}("foo") # これもOK convert(String, [0x66, 0x6f, 0x6f]) convert(String, [0xce, 0xb1, 0xce, 0xb2, 0xce, 0xb3]) String([0x66, 0x6f, 0x6f]) # これもOK replace("hello, world", "world", "there") replace("a5b4ra221ca1d856ab86r7a7", r"\d+", "") collect("foo") collect("αβγ") "foo" * "bar" string("foo", 123) join(["foo", "bar", "baz"], ",") split("foo,bar,baz", ",") split("123 45 567", r"\s+") rpad(123, 5) lpad(123, 5) println(" left aligned: ", rpad(123, 5)) println("right aligned: ", lpad(123, 5)) @sprintf("%5d", 123) chomp("foo bar\n") chomp("foo bar\r\n") strip(" foo bar ") # 両側 lstrip(" foo bar ") # 左のみ rstrip(" foo bar ") # 右のみ uppercase("foo") lowercase("FOO") readstring("data/julia.md") readlines("data/julia.md") # 改行で分割 i = 1 for line in eachline("data/julia.md") println(i, ": ", line) i += 1 end read("data/julia.md") isfile("data/julia.md") isfile("data/python.md") filesize("data/julia.md") # 単位はバイト file = open("data/julia.md") isopen(file) # ファイルが開いているか判定する readline(file) # 1行読み込む close(file) isopen(file) file = open("data/julia.md") position(file) # 最初の位置は0 sizeof(readline(file)) # 1行(改行含む)を読む position(file) # 1行分読み込み位置が進む eof(file) # 読み込み位置は末尾か判定 sizeof(read(file)) # 残りすべてを読み込む eof(file) # open ... do ... endはdoの中でエラーが起きても必ずファイルを閉じる open("data/julia.md") do file println(readline(file)) div(1, 0) # エラー! end using CodecZlib # https://github.com/bicycle1885/CodecZlib.jl file = GzipDecompressionStream(open("data/julia.md.gz")) readlines(file) close(file) write("data/output.txt", "アブラカダブラ\n") readstring("data/output.txt") file = open("data/output.txt", "w") println(file, "寿限無寿限無") close(file) readstring("data/output.txt") file = open("data/object.dat", "w") serialize(file, "テキスト") serialize(file, 3.14) serialize(file, [10, 20, 30]) serialize(file, Dict("愛里寿" => "センチュリオン", "ミカ" => "BT-42")) close(file) file = open("data/object.dat") while !eof(file) @show deserialize(file) end close(file) run(`echo "hello"`) readstring(`ls data`) read(`ls data`) pipe, proc = open(`ls data`) # パイプとプロセス while !eof(pipe) println(readline(pipe)) end proc filter(isodd, [1,2,3,4,5]) filter(x->x>2, [1,2,3,4,5]) any(isodd, [1,2,3,4]) any(isodd, [2,4,6,8]) all(isodd, [1,2,3,4]) all(isodd, [1,3,5,7]) map(sin, [0.0, 1.0, 2.0, 3.0]) sin.([0.0, 1.0, 2.0, 3.0]) foldl(+, 0, [1,2,3]) # 総和の計算 foldl(+, [1,2,3]) # 第二引数は省略可 # 分岐する式の作成 foldr((x, r)->:(if x == $(x); print($(x)); else; $(r); end), :(nothing), [1,2,3]) sort(randn(100000)) # コンパイルのため測定前に一度実行する @elapsed sort(randn(100000)) # 単位は秒 [@elapsed sort(randn(100000)) for _ in 1:10] sort(randn(100000)) # コンパイルのため測定前に一度実行する @allocated sort(randn(100000)) # 単位はバイト [@allocated sort(randn(100000)) for _ in 1:10] sort(randn(100000)) # コンパイルのため測定前に一度実行する @time sort(randn(100000)); for _ in 1:10 @time sort(randn(100000)) end 100000 * sizeof(Float64) * 2 / 1024^2 # 100000要素の倍精度浮動小数点数のメモリ割り当て量 (MiB) using BenchmarkTools # https://github.com/JuliaCI/BenchmarkTools.jl @benchmark sort(randn(100000)) @benchmark sort(randn(10)) function bubblesort(x) x = copy(x) swapped = true while swapped swapped = false for i in 1:endof(x)-1 if x[i+1] < x[i] x[i+1], x[i] = x[i], x[i+1] swapped = true end end end return x end bubblesort(randn(10)) x = randn(10000) Profile.clear() @profile bubblesort(x); Profile.print() isodd(41) # 奇数 iseven(42) # 偶数 using Primes # https://github.com/JuliaMath/Primes.jl isprime(42) isprime(43) using Primes # https://github.com/JuliaMath/Primes.jl primes(50) div(42, 5) 42 / 5 # 整数 / 整数 = 浮動小数点数 になるので注意 42 % 5 rem(42, 5) # 上と同じ abs(-42) abs(42) xor(42, 35) 42 ⊻ 35 # 上と同じ(\xor) x = [1.0, 2.0, 3.0] y = [-1.0, 3.0, 0.0] x + y x - y 3.2x x' x'' # 2回でもとに戻る dot(x, x) x ⋅ x # 上と同じ (\cdot) x'x x * x' diagm([1.0, 2.0, 3.0]) # 通常の行列の型 Diagonal([1.0, 2.0, 3.0]) # 対角行列の型 A = randn(3, 3) B = randn(3, 3) A * B # 通常の行列積 At_mul_B(A, B) # Aを転置して掛ける A'B # 上と同じ A_mul_Bt(A, B) # Bを転置して掛ける A * B' # 上と同じ At_mul_Bt(A, B) # AもBも転置して掛ける A'B' # 上と同じ X = [5.0 2.0; -2.0 3.0] eigvals(X) eigvecs(X) # 複素数の固有ベクトル eigvals(X'X) # 固有値はすべて正なので正定値行列 eigvecs(X'X) # 正定値行列に対しては実数の固有ベクトル A = [3.0 2.0 -1.0 2.0 -2.0 4.0 -1.0 0.5 -1.0] b = [1.0, -2.0, 0.0] x = A \ b # A x = b の解 A * x ≈ b # 解の確認 rand() rand(30) randn() randn(30) import Distributions ## https://github.com/JuliaStats/Distributions.jl g = Distributions.Gamma(1.0, 2.0) # ガンマ分布 rand(g, 10) p = Distributions.Poisson(10) # ポアソン分布 rand(p, 10) rand(1:20) # 1-20の値から1個サンプリング rand(1:20, 10) # 1~20の値から10個サンプリング using StatsBase # https://github.com/JuliaStats/StatsBase.jl sample(1:20, 10, replace=false) # 非復元抽出 mean(randn(100)) var(randn(100)) median(exp.(randn(100))) x = exp.(randn(100)); quantile(x, 0.1) quantile(x, 0.25) for q in linspace(0, 1, 11) println(q, ": ", quantile(x, q)) end A = randn(5, 3) maximum(A) # 全要素の最大値 (最小値はminimum) maximum(A, 2) # 行最大 maximum(A, 1) # 列最大 A = randn(5, 3) + 10 A .- mean(A, 2) # 行平均を引く A .- mean(A, 1) # 列平均を引く X = [3.0 5.8 1.1; 1.0 4.2 0.1] cov(X, 1) # 各行がサンプル cov(X, 2) # 各列がサンプル cor(X, 2) # ピアソンの相関係数の行列 X = randn(20, 4) b = [-1.0, 1.0, 2.0, 3.0] y = X * b + randn(20) * 0.1 (X'X)\X'*y Q, R = qr(X) R\(Q'y) using Roots # https://github.com/JuliaMath/Roots.jl fzero(log, 0, 10) fzero(x -> sin(x - 3), 2, 4) using Interpolations f(x) = sin(x) * exp(-x) xs = linspace(-3, 3, 8) itp = interpolate([f(x) for x in xs], BSpline(Cubic(Line())), OnCell()) scl = scale(itp, xs) g = x->scl[x] f(1) g(1) using Gadfly plot(layer([f, g], -3, 3), layer(x=xs, y=f.(xs), Geom.point)) import ForwardDiff # https://github.com/JuliaDiff/ForwardDiff.jl f(x) = sin(x) * exp(-x) f′(x) = ForwardDiff.derivative(f, x) f(1.0) f′(1.0) using Gadfly plot([f, f′], -3, 3) import ReverseDiff # https://github.com/JuliaDiff/ReverseDiff.jl f(x) = 2dot(x, x) + sum(x) f′(x) = ReverseDiff.gradient(f, x) f′(zeros(3)) f′(ones(3)) using Optim # https://github.com/JuliaNLSolvers/Optim.jl # 2変数のRosenbrock関数 https://en.wikipedia.org/wiki/Rosenbrock_function f(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2 optimize(f, zeros(2)) optimize(f, zeros(2), BFGS())