You are on page 1of 10

Julia Language Notebook

(use at your own risk)
What is Julia?

Basic commands

julia # start julia

pwd() # check working directory

cd("../../folder1/folder2") # change working directory

readdir() # list all items in current directory

include("filename") # run a Julia script file

?command_name # help for "command_name"

Pkg.add("package_name") # add a package

Pkg.rm("package_name") # remove a package

Pkg.status() # list all installed packages

using package_name # load a package

showall(x) # show all elements of x

whos() # get a list of current variables in the memory

Numbers

round(x,4) # round the number x with 4 decimals

floor(x,4) # round down x with 4 decimals

ceil(x,4) # round up x with 4 decimals

trunc(x,4) # round x toward zero with 4 decimals

iround(x); itrunc(x); # similar, but return integers


ifloor(x); iceil(x);

x%y; rem(x,y); mod(x,y); # remainder when divide x by y: rem(1.2,0.5)=0.2

div(x,y) # truncated division: div(1.2,0.5)=2.0

typemax(Int64); # max/min value of a type


typemin(Int64)

1<2<=3>=2<4!=5 # chaining comparison:


# use && for scalar comparison,
# use & for element-wise comparison

sqrt(x); cbrt(x) # square and cube roots

atan2(y,x) # return the angle (rad) between the x-axis and the point (x,y)

1//2+1//3 # fraction operator: returns 5//6

max(a,b,c); # returns maximum, similar for min, minimum


maximum([a,b,c]);
Complex number

1+2im

(1+2im)*(2-3im)

e^(im*pi/4)

# Note:

3/4im == 3/(4*im) == -(3/4*im)

Strings

string(st1,st2,st3) # concaternate multiple strings

join(Ar,";") # join an array of strings with the given delimiter


Ex: x=[1,2,3]; join(x,"-") ->
"1-2-3"

@sprintf("%4d %10s # combine the integer number num_1, the string st, and the real number
%7.3f",num_1,st,num_2) num_2, then output as a string

@printf("%4d %10s # same as above, but output to screen


%7.3f",num_1,st,num_2)

strftime("%Y-%m-%d-%H-%M-%S", # return the current time and date in a string:


time()) year-month-date-(24-hour clock)-minute-second

strftime("%Y-%m-%d-%I-%M-%S", # same as above, but 12-hour clock


time())

print_with_color(:blue,"The # print a string in blue. Similarly,


color is blue") :red, :green, :gray, :yellow, :cyan, :magenta, :black

If­statement

if (k<50)||((k<1000)&&(mod(k,10)==0))||(mod(k,100)==0)
    println(k);
end

if x < y
    println("x is less than y");
elseif x > y
    println("x is greater than y");
else
    println("x is equal to y");
end

x='D';
if x in ['A':'H']
    println("x is between 'A' and 'H');
else
    println("x is not between 'A' and 'H'");
end

x="D";
if x in ["A","bcd","H"]
    println("x is in the set ["A","bcd","H"]");
else
    println("x is not in the set ["A","bcd","H"]");
end
For­statement

for k=1:2:10
    println("k = ",k);
    sleep(1);  # pause for 1 second
end

for i in [1,4,0] println(i); end

for s in ["foo","bar","baz"] println(s); end

While­statement

i=0; while (i<100) i+=3; println("i = ",i); end

Match package

# one-time setup
Pkg.add("Match");

# usage
using Match;
@match item begin
    pattern1 => {statement_1; statement_2;}
    partern2, if (cond) end => result2;
    partern3 || partern4 => result3;
    _=> default_result;
end

Function declaration

function polar(x,y)
    # return polar coordinates
    r = hypot(x,y); # r= sqrt(x^2+y^2);
    theta = atan2(y,x);
    return r, theta;
end

r, th = polar(2,1); # call function

Variable scope

a=8; b=[1,3];
if (a>1)
    a=11; b=[2,10,5];
end
for i=1:3 a+=2;end
println("Before the function call: a=",a," b=",b');

function check()
    a=5; b=[3,2,1];
    println("Inside the function: a=",a," b=",b');
end

check(); # call the function


println("After the function call: a=",a," b=",b');

Read/write Text files

f_stream = open(fname,"w"); # write to a new file


print(f_stream, x," ",y," ", z, "\n");
println(f_stream, u, " ",v);
close(f_stream);

file = open(fname,"a"); # write to an existing file ("a"="append")


print(file, x," ",y," ", z, "\n");
close(file);

A = readdlm(filename::string, ';') # read an array/matrix from file with delimiter ';'

writedlm(filename,array, ';') # write an array/matrix to file

A = readcsv(filename) # read an array/matrix from file with delimiter ';'

writecsv(filename, A) # write an array/matrix to file with delimiter ';'

Read/write Matlab files (HDF5 package)  [more]

Pkg.add("HDF5"); # one-time setup

using HDF5, JLD; # load HDF5

k=1; x=10; y=[3,8]; # simple read/write


fname=@sprintf("../data/file_number_%i",k);  
@save fname x y;
@load eval(fname);
@load fname y x;

jldopen(fname,"w") do file # write a new file


    @write file x y;
end

jldopen(fname,"r") do file # read an existing file


    @read file y;
end

m=[1:0.2:2]; # read and write to an existing file


jldopen(fname,"r+") do file
    @write file m;
    @read file x;
end

Data Type: Dictionary  [more]

dict = {"a"=>1, "b"=>2, "c"=>3} # Create a simple dictionary

Dict{Any,Any} with 3 entries:


"c" => 3
"b" => 2
"a" => 1

dict["a"] # Look up a value

julia> get(dict, "a", 0) # Look up and return 0 if nothing is found


1

julia> get(dict, "1", 0)


0

dict["a"] = 10 # Change a value or add new entries

dict["d"] = 5

delete!(dict, "d") # Delete an entry


keys(dict) # Get all keys

KeyIterator for a Dict{Any,Any} with 3 entries. Keys:


"c"
"b"
"a"

values(dict) # Get all values

ValueIterator for a Dict{Any,Any} with 3 entries. Values:


3
2
1

K=[k for k in keys(dict)] # put keys/values into an array

V=[k for k in values(dict)]

Arrays and Matrices  [more]

size(A) # returns the dimensions of a matrix A

size(A,1) # returns the number of rows of a matrix A

size(A,2) # returns the number or columns of a matrix A

A=rand(3,4) # create a random matrix 3x4

A=randn(5) # random values with normal distribution

A=zeros(n); or zeros(m,n); # create a zero column-vector or a zero matrix

A=ones(n);  or ones(m,n); #create a column-vector or a matrix whose entries are all 1

A=eye(3);   or eye(3,5); # create the identity matrix 3x3 or 3x5

A=repmat(B,m,n) # repeating matrix B m times in (rows) and n times in (columns)

a=[4,3,5]; b=[2 3 1]; # a is a column vector; b is a 1x3 matrix

A=[1 2 3; 4 5 6]; # A is a 2x3 matrix

A[i,j] # value at row i and column j

A[i,:]; B[:,j] # row i of A; column j of B

vcat(A,B); or [A; B]; # combine matrices vertically

hcat(A,B); or [A B]; # combine matrices horizontally

reshape([1:6],2,3); # reshape a vector/matrix into a 2x3 matrix

A=[1 2 3; 4 5 6; 7 8 9];

B=diag(A);     # return B=[1,5,9]

C=diagm(B);    # return a 3x3 matrix with diagonal entries 1,5,9

A=[5 3; 3 4];

isposdef(A);     # check positive definite


ishermitian(A);     # check hermitian

chol(A);     # Cholesky factorization

Simple Statistics

x=rand(100);
mean(x);
mean(x[1:50]);
median(x);
std(x);
var(x);

quantile(x,p);  # general quantile for 0 < p < 1

for example,
    quantile(x,0.25);  # first quartile
    quantile(x,0.5);   # second quartile = median
    quantile(x,0.75);  # third quartile

Plotting with Gaston (OS X, Linux)

First, install Gnuplot   [instruction]

# (run in Julia terminal) one-time setup

Pkg.add("Gaston");

# in Julia terminal, load Gaston to use

using Gaston;
set_terminal("x11");
# or set_terminal("wxt");

Gaston: 2D plots

x = [0:0.1:10];
## or x = linspace(0,10,101);
y1 = sin(x); y2 = cos(x);

figure(k);
#or Gaston.figure(k); #k=1,2,...

plot(x,y1, "plotstyle", "points", "pointsize", 1.5, "marker", "etrianup", "color", "blue", "legend",
"sin(x)", "title", "sin(x) vs. cos(x)", x, y2, "plotstyle", "linespoints, "pointsize", 1.5, "marker",
"fsquare", "color", "#ff0000", "legend", "cos(x)");

Gaston: 3D plots

gnuplot_send("set view 60, 30");

f=(x,y)->max(abs(x),-abs(y)+1);

surf(-3:0.1:3,-3:0.1:3,f,"plotstyle","linespoints","color","blue","legend","f(x,y)");

Gaston: plot parameters

legend, title, any string


xlabel, ylabel, zlabel   

plotstyle lines, linespoints, points, impulses,


errorbars, errorlines, pm3d, boxes, image, rgbimage
color any gnuplot color name, or "#RRGGBB"
(run "show colornames" in gnuplot terminal
to get a list of valid color names)

marker +, x, *, esquare, fsquare, ecircle, fcircle,


etrianup, ftrianup, etriandn, ftriandn, edmd, fdmd

linewidth, pointsize    any real number

axis normal, semilogx, semilogy, loglog

Gaston: mid­level plotting

x=[0:0.1:10];
## or x = linspace(0,10,101);
y1 = sin(x); y2 = cos(x);

plot(x,y1,"legend","sin(x)");

c2=Gaston.CurveConf();
c2.legend="cos(x)";
c2.plotstyle="linespoints";
c2.color="blue";
c2.marker="ecircle";
c2.linewidth=1.5;
c2.pointsize=1;

# or c2 = Gaston.CurveConf("cos(x)","linespoints","blue","ecircle",1.5,1);

Gaston.addcoords(x,y2,c2);
Gaston.llplot();

Load Gaston automatically when starting Julia

In Ubuntu or Mac OS terminal, run:

  echo 'using Gaston; set_terminal("x11")' > .juliarc.jl

  (or replace "x11" by "wxt" depending on the hardware)

Run Julia from Mac OS terminal

open ~/.bash_profile (or ~/.bashrc) and insert:

alias julia="/Applications/Julia-0.3.8.app/Contents/Resources/julia/bin/julia"
export PATH

then save and exit

Plotting with Winston (Windows)   [more]

# Intallation

Pkg.add("Winston");

# load package before use

using Winston;

# basic plot for two vectors x and y

plot(x,y)
# add to current plot

oplot(x2,y2)

# plot in log scale

semilogy(y);    # y-axis in log scale


semilogy(x,y)

semilogx(y);    # x-axis in log scale


semilogx(x,y);

loglog(y);      # both axes in log scale


loglog(x,y);

# Add title and legends

figure("An example");
semilogy([1:100]);
title("graph of y=x");
legend("y=x");

# Multiple plots

z=[1:100];
figure();    # create an empty plot and return an ID
semilogy(z);

figure();    # create another empty plot and return an ID


semilogx(z);

figure(1);    # switch to figure 1


plot(z);

closefig(1);    # close figure 1


closefig(2);

# Example 1

x = linspace(0, 3pi, 100);


c = cos(x);
s = sin(x);

p = FramedPlot(title="title!", xlabel="\\Sigma x^2_i", ylabel="\\Theta_i");

add(p, FillBetween(x, c, x, s));


add(p, Curve(x, c, color="red"));
add(p, Curve(x, s, color="blue"));

# Example 2

p = FramedPlot( aspect_ratio=1, xrange=(0,100), yrange=(0,100) )

n = 21
x = linspace(0, 100, n)
yA = 40 .+ 10randn(n)
yB = x .+ 5randn(n)

a = Points(x, yA, kind="circle")


setattr(a, label="a points")

b = Points(x, yB)
setattr(b, label="b points")
style(b, kind="filled circle")

s = Slope(1, (0,0), kind="dotted")


setattr(s, label="slope")

l = Legend(.1, .9, {a,b,s})

add(p, s, a, b, l)

# Example 3

# Example 4

# Example 5

Load and view images  [more]

# Installation

Pkg.add("Images")
Pkg.add("TestImages")
Pkg.add("ImageView")

# Load with other useful packages

using Images, Color, FixedPointNumbers, ImageView, TestImages

TestImages package contains several images located at

~/.julia/<version>/TestImages/Images/

For examples, "lena", "cameraman", "mandril", etc.

# Usage

img = imread("name.jpg")    # load local image

img = testimage("lena")    # load a test image

g=convert(Array{Gray},img);    # convert to grayscale

view(img, pixelspacing = [1,1], flipy=true)

view(img, pixelspacing = [1,1], xy=["y","x"])

view(g)

# converting images to and from real matrices

A = imread("<grayscale_image>")

B = convert(Array, A)    # convert an image to an array

C = float(B)    # convert an array to a real matrix

D = convert(Image, C)    # convert a real matrix to an image

# write an matrix to an image file

imwrite(A,"test_image.jpg")

Accessing image information using Color package  [more]
# Color structure

Mathematical programming  [more]

Pkg.add("Clp");    # Installation
Pkg.add("JuMP");

# Solve a simple LP:


# max 5x + 3y subject to
# 1x + 5y <= 3
# 0 <= x <= 3
# 0 <= y <= 20

using JuMP;
m = Model();
@defVar(m, 0 <= x <= 2);
@defVar(m, 0 <= y <= 30);
@setObjective(m, Max, 5x + 3y);
@addConstraint(m, 1x + 5y <= 3.0);
print(m);
status = solve(m);
println("Objective value = ", getObjectiveValue(m));
println("x = ", getValue(x));
println("y = ", getValue(y));

You might also like