Julia Basics

Here is some italic text. Even equations $\int_0^1 \frac{1}{1+x^2} dx$.

I can use Julia as a calculator:

In [2]:
3 + 4
Out[2]:
7
In [3]:
3 * 4
Out[3]:
12
In [4]:
3^4
Out[4]:
81
In [5]:
sin(3)
Out[5]:
0.1411200080598672
In [6]:
1 / (1 + sin(7))
Out[6]:
0.6035051827052901

Variables

In [7]:
x = 17
Out[7]:
17
In [9]:
y = sin(x)
Out[9]:
-0.9613974918795568
In [44]:
α = 3.74 # Unicode variable names — type it by "\alpha<tab>"
Out[44]:
3.74
In [45]:
α̂₂ = 3
Out[45]:
3

A complex number $3 + 5i$:

In [83]:
z = 3 + 5im
Out[83]:
3 + 5im
In [84]:
z^3
Out[84]:
-198 + 10im
In [85]:
exp(z) # compute eᶻ
Out[85]:
5.697507299833739 - 19.26050892528742im
In [86]:
sin(z)
Out[86]:
10.472508533940392 - 73.46062169567367im

Online help:

In [46]:
?sin
search: sin sinh sind sinc sinpi sincos sincosd asin using isinf asinh asind

Out[46]:
sin(x)

Compute sine of x, where x is in radians.


sin(A::AbstractMatrix)

Compute the matrix sine of a square matrix A.

If A is symmetric or Hermitian, its eigendecomposition (eigen) is used to compute the sine. Otherwise, the sine is determined by calling exp.

Examples

jldoctest
julia> sin(fill(1.0, (2,2)))
2×2 Array{Float64,2}:
 0.454649  0.454649
 0.454649  0.454649
In [47]:
?α̂₂
"α̂₂" can be typed by \alpha<tab>\hat<tab>\_2<tab>

search: α̂

Out[47]:

No documentation found.

α̂₂ is of type Int64.

Summary

primitive type Int64 <: Signed

Supertype Hierarchy

Int64 <: Signed <: Integer <: Real <: Number <: Any

Vectors

In [10]:
x = [1, 17, 32, 15]  # elements separated by commas
Out[10]:
4-element Array{Int64,1}:
  1
 17
 32
 15

Array{Int64,1} is a 1-dimensional array (a "vector") of 64-bit integers (Int64).

In [12]:
y = [15, 2, 6, -9]
Out[12]:
4-element Array{Int64,1}:
 15
  2
  6
 -9
In [13]:
x + y
Out[13]:
4-element Array{Int64,1}:
 16
 19
 38
  6
In [14]:
x * y # not allowed: vector * vector is not a linear-algebra operation
MethodError: no method matching *(::Array{Int64,1}, ::Array{Int64,1})
Closest candidates are:
  *(::Any, ::Any, !Matched::Any, !Matched::Any...) at operators.jl:538
  *(!Matched::LinearAlgebra.Adjoint{var"#s826",var"#s8261"} where var"#s8261"<:(AbstractArray{T,1} where T) where var"#s826"<:Number, ::AbstractArray{var"#s825",1} where var"#s825"<:Number) at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.5/LinearAlgebra/src/adjtrans.jl:283
  *(!Matched::LinearAlgebra.Transpose{T,var"#s826"} where var"#s826"<:(AbstractArray{T,1} where T), ::AbstractArray{T,1}) where T<:Real at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.5/LinearAlgebra/src/adjtrans.jl:284
  ...

Stacktrace:
 [1] top-level scope at In[14]:1
 [2] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1091
 [3] execute_code(::String, ::String) at /Users/stevenj/.julia/dev/IJulia/src/execute_request.jl:27
 [4] execute_request(::ZMQ.Socket, ::IJulia.Msg) at /Users/stevenj/.julia/dev/IJulia/src/execute_request.jl:86
 [5] #invokelatest#1 at ./essentials.jl:710 [inlined]
 [6] invokelatest at ./essentials.jl:709 [inlined]
 [7] eventloop(::ZMQ.Socket) at /Users/stevenj/.julia/dev/IJulia/src/eventloop.jl:8
 [8] (::IJulia.var"#15#18")() at ./task.jl:356
In [17]:
transpose(x)
Out[17]:
1×4 LinearAlgebra.Transpose{Int64,Array{Int64,1}}:
 1  17  32  15
In [18]:
transpose(x) * y # allowed = a dot product
Out[18]:
106
In [19]:
x .* y # elementwise product
Out[19]:
4-element Array{Int64,1}:
   15
   34
  192
 -135
In [22]:
float(y) .^ x
Out[22]:
4-element Array{Float64,1}:
     15.0
 131072.0
      7.958661109946401e24
     -2.05891132094649e14
In [24]:
float(y)
Out[24]:
4-element Array{Float64,1}:
 15.0
  2.0
  6.0
 -9.0
In [26]:
z = [3.7, 4.2, 6.1]
Out[26]:
3-element Array{Float64,1}:
 3.7
 4.2
 6.1
In [29]:
z .^ [0,1,2]
Out[29]:
3-element Array{Float64,1}:
  1.0
  4.2
 37.209999999999994
In [30]:
z .^ transpose([0,1,2]) # a Vandermonde matrix
Out[30]:
3×3 Array{Float64,2}:
 1.0  3.7  13.69
 1.0  4.2  17.64
 1.0  6.1  37.21
In [31]:
z .^ [0 1 2]
Out[31]:
3×3 Array{Float64,2}:
 1.0  3.7  13.69
 1.0  4.2  17.64
 1.0  6.1  37.21
In [33]:
[0 1 2] # another row vector
Out[33]:
1×3 Array{Int64,2}:
 0  1  2
In [36]:
@show x
x[2] # second element
x = [1, 17, 32, 15]
Out[36]:
17
In [38]:
x[2:3] # elements 2 to 3 — "slicing"
Out[38]:
2-element Array{Int64,1}:
 17
 32
In [39]:
x[2:4] # elements 2,3,4
Out[39]:
3-element Array{Int64,1}:
 17
 32
 15
In [40]:
2:4
Out[40]:
2:4
In [42]:
0:4 # analogous to range(5) in Python
Out[42]:
0:4
In [43]:
collect(0:4)
Out[43]:
5-element Array{Int64,1}:
 0
 1
 2
 3
 4
In [62]:
y .^ 3 # elementwise cube
Out[62]:
4-element Array{Int64,1}:
 3375
    8
  216
 -729
In [64]:
sin.(y) # elementwise sin
Out[64]:
4-element Array{Float64,1}:
  0.6502878401571168
  0.9092974268256817
 -0.27941549819892586
 -0.4121184852417566
In [87]:
rand(7) # 7 random numbers in [0,1)
Out[87]:
7-element Array{Float64,1}:
 0.9895925568529049
 0.43720897273586745
 0.18692127626397315
 0.5248400288925346
 0.7725784322036084
 0.2755926598616645
 0.046487055457531845
In [91]:
randn(7) # 7 normally-distributed random numbers (mean 0, std. dev. 1)
Out[91]:
7-element Array{Float64,1}:
 -0.7766970200438933
  0.8375893322814147
 -1.0161992755239175
 -1.4656970471375195
 -0.2380323626857652
  0.3324373560431813
 -0.2545786106508578
In [94]:
collect(0:2:7) # 0 to 7 in steps of 2
Out[94]:
4-element Array{Int64,1}:
 0
 2
 4
 6
In [95]:
collect(0:0.1:7) # 0 to 7 in steps of 0.1
Out[95]:
71-element Array{Float64,1}:
 0.0
 0.1
 0.2
 0.3
 0.4
 0.5
 0.6
 0.7
 0.8
 0.9
 1.0
 1.1
 1.2
 ⋮
 5.9
 6.0
 6.1
 6.2
 6.3
 6.4
 6.5
 6.6
 6.7
 6.8
 6.9
 7.0
In [97]:
r = range(0, 2π, length=50) # 50 numbers from 0 to 2π, equally spaced
Out[97]:
0.0:0.1282282715750936:6.283185307179586
In [98]:
collect(r)
Out[98]:
50-element Array{Float64,1}:
 0.0
 0.1282282715750936
 0.2564565431501872
 0.38468481472528077
 0.5129130863003744
 0.641141357875468
 0.7693696294505615
 0.8975979010256552
 1.0258261726007487
 1.1540544441758425
 1.282282715750936
 1.4105109873260295
 1.538739258901123
 ⋮
 4.872674319853557
 5.00090259142865
 5.129130863003744
 5.257359134578837
 5.385587406153931
 5.513815677729025
 5.642043949304118
 5.770272220879212
 5.898500492454305
 6.026728764029399
 6.154957035604492
 6.283185307179586
In [99]:
r = range(0, 2π, length=10^8) # not computed explicitly
Out[99]:
0.0:6.28318537001144e-8:6.283185307179586
In [101]:
collect(r[1:10])
Out[101]:
10-element Array{Float64,1}:
 0.0
 6.28318537001144e-8
 1.256637074002288e-7
 1.884955611003432e-7
 2.513274148004576e-7
 3.14159268500572e-7
 3.769911222006864e-7
 4.398229759008008e-7
 5.026548296009151e-7
 5.654866833010296e-7

Matrices

In [48]:
A = [1 3 7
     4 7 2
     0 1 1]
Out[48]:
3×3 Array{Int64,2}:
 1  3  7
 4  7  2
 0  1  1

Notice that the type is Array{Int64,2} — the 2 here is for a 2d array, a "matrix"

In [50]:
b = [3, 2, 1] # a vector
Out[50]:
3-element Array{Int64,1}:
 3
 2
 1
In [51]:
A * b # matrix-vector product
Out[51]:
3-element Array{Int64,1}:
 16
 28
  3
In [52]:
inv(A)
Out[52]:
3×3 Array{Float64,2}:
  0.238095   0.190476  -2.04762
 -0.190476   0.047619   1.2381
  0.190476  -0.047619  -0.238095

Let's solve a linear system: $$ Ax = b $$ for $x = A^{-1} b$:

In [53]:
x = inv(A) * b
Out[53]:
3-element Array{Float64,1}:
 -0.9523809523809521
  0.761904761904762
  0.23809523809523808
In [54]:
A * x
Out[54]:
3-element Array{Float64,1}:
 3.0000000000000004
 2.0000000000000018
 1.0
In [56]:
A * x - b # not zero due to roundoff errors — more about this in 18.330 or 18.335 in spring
Out[56]:
3-element Array{Float64,1}:
 4.440892098500626e-16
 1.7763568394002505e-15
 0.0

Alternatively:

In [57]:
x = A \ b # effectively equivalent to inv(A) * b, but faster and better
Out[57]:
3-element Array{Float64,1}:
 -0.9523809523809528
  0.7619047619047621
  0.23809523809523808
In [59]:
A * x - b # slightly different (smaller in this case)
Out[59]:
3-element Array{Float64,1}:
 0.0
 0.0
 2.220446049250313e-16
In [65]:
sin.(A) # elementwise sine
Out[65]:
3×3 Array{Float64,2}:
  0.841471  0.14112   0.656987
 -0.756802  0.656987  0.909297
  0.0       0.841471  0.841471
In [70]:
sin(A) # is this meaningful????
Out[70]:
3×3 Array{Float64,2}:
 -0.888487  -0.296349   6.91956
  0.962251   0.264022  -3.59102
 -0.581735   0.240563   0.565852

In 18.06 (or maybe 18.S096), you'll eventually learn that $\sin(A)$ is perfectly meaningful for a square matrix. It's defined by the Taylor series: $$ \sin(A) = A - \frac{A^3}{3!} + \frac{A^5}{5!} - \frac{A^7}{7!} + \cdots $$

Functions

In [74]:
function f(x)
    return 3x^3 - 5x^2 + sin(x) - x
end
Out[74]:
f (generic function with 1 method)
In [72]:
f(3)
Out[72]:
34.141120008059865
In [75]:
f(A)
Out[75]:
3×3 Array{Float64,2}:
 344.112    669.704  418.92
 688.962   1421.26   956.409
  87.4183   172.241  125.566
In [77]:
f.(x) # applied elementwise
Out[77]:
3-element Array{Float64,1}:
 -6.989077393122971
 -1.6472437070737587
 -0.24519753391390525
In [78]:
f.(A)
Out[78]:
3×3 Array{Float64,2}:
  -2.15853   33.1411   777.657
 107.243    777.657      2.9093
   0.0       -2.15853   -2.15853
In [79]:
g(x) = 4x^3 - 5x^2 + 6x + 2 # one-line function definition
Out[79]:
g (generic function with 1 method)
In [80]:
g.(A)
Out[80]:
3×3 Array{Int64,2}:
   7    83  1171
 202  1171    26
   2     7     7

More Linear Algebra

Most linear-algebra routines are in the LinearAlgebra standard library:

In [102]:
using LinearAlgebra # similar to "from LinearAlgebra import *" in Python
In [104]:
eigvals(A) # eigenvalues
Out[104]:
3-element Array{Complex{Float64},1}:
 -0.07094370057923445 - 1.5139635518670342im
 -0.07094370057923445 + 1.5139635518670342im
    9.141887401158474 + 0.0im
In [106]:
F = eigen(A) # eigenvectors and eigenvalues
Out[106]:
Eigen{Complex{Float64},Complex{Float64},Array{Complex{Float64},2},Array{Complex{Float64},1}}
values:
3-element Array{Complex{Float64},1}:
 -0.07094370057923445 - 1.5139635518670342im
 -0.07094370057923445 + 1.5139635518670342im
    9.141887401158474 + 0.0im
vectors:
3×3 Array{Complex{Float64},2}:
  0.834342-0.0im        0.834342+0.0im        0.42575+0.0im
 -0.454852+0.168903im  -0.454852-0.168903im  0.898092+0.0im
 0.0672889-0.252839im  0.0672889+0.252839im  0.110305+0.0im
In [107]:
F.values # the eigenvalues
Out[107]:
3-element Array{Complex{Float64},1}:
 -0.07094370057923445 - 1.5139635518670342im
 -0.07094370057923445 + 1.5139635518670342im
    9.141887401158474 + 0.0im
In [108]:
F.vectors # the eigenvectors
Out[108]:
3×3 Array{Complex{Float64},2}:
  0.834342-0.0im        0.834342+0.0im        0.42575+0.0im
 -0.454852+0.168903im  -0.454852-0.168903im  0.898092+0.0im
 0.0672889-0.252839im  0.0672889+0.252839im  0.110305+0.0im
In [109]:
qr(A) # QR factorization = Gram-Schmidt orthogonalization
Out[109]:
LinearAlgebra.QRCompactWY{Float64,Array{Float64,2}}
Q factor:
3×3 LinearAlgebra.QRCompactWYQ{Float64,Array{Float64,2}}:
 -0.242536   0.748481  -0.617213
 -0.970143  -0.18712    0.154303
  0.0        0.636209   0.771517
R factor:
3×3 Array{Float64,2}:
 -4.12311  -7.5186   -3.63803
  0.0       1.57181   5.50134
  0.0       0.0      -3.24037
In [110]:
lu(A) # Gaussian elimination = LU factorization
Out[110]:
LU{Float64,Array{Float64,2}}
L factor:
3×3 Array{Float64,2}:
 1.0   0.0  0.0
 0.25  1.0  0.0
 0.0   0.8  1.0
U factor:
3×3 Array{Float64,2}:
 4.0  7.0    2.0
 0.0  1.25   6.5
 0.0  0.0   -4.2
In [111]:
svd(A)
Out[111]:
SVD{Float64,Float64,Array{Float64,2}}
U factor:
3×3 Array{Float64,2}:
 -0.657006   0.742232   -0.132041
 -0.742831  -0.667249   -0.0545987
 -0.128629   0.0622125   0.989739
singular values:
3-element Array{Float64,1}:
 10.249509228237182
  4.9777646539733755
  0.4116061587661843
Vt factor:
3×3 Array{Float64,2}:
 -0.354     -0.712177  -0.606208
 -0.387074  -0.478494   0.788173
 -0.851386   0.513661  -0.106278

A little plotting

You must load a plotting library, similar to Python.

There are lots to choose from. If you are used to Python, you've probably used Matplotlib, and you can call Matplotlib in Julia via PyPlot:

In [114]:
using PyPlot
In [116]:
plot(x, "bo-")
Out[116]:
1-element Array{PyCall.PyObject,1}:
 PyObject <matplotlib.lines.Line2D object at 0x7ffd3f6b1fd0>
In [129]:
x = range(0, 2π, length=1000)
y = sin.(3x + 4cos.(2x))
plot(x / 2π, y, "r-")
plot(x / 2π, y.^2, "b-")
plot(x / 2π, 1 ./ sqrt.(1 .+ y.^2), "b-")
xlabel("x / 2π")
ylabel("our funny function")
title("our second plot")
legend([L"y", L"y^2", L"\frac{1}{\sqrt{1+y^2}}"])
Out[129]:
PyObject <matplotlib.legend.Legend object at 0x7ffd472bf790>
In [125]:
?plot
search: plot plot3D plotfile plot_date plot_trisurf plot_surface plot_wireframe

Out[125]:
Plot y versus x as lines and/or markers.

Call signatures::

    plot([x], y, [fmt], *, data=None, **kwargs)
    plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

The coordinates of the points or line nodes are given by *x*, *y*.

The optional parameter *fmt* is a convenient way for defining basic
formatting like color, marker and linestyle. It's a shortcut string
notation described in the *Notes* section below.

>>> plot(x, y)        # plot x and y using default line style and color
>>> plot(x, y, 'bo')  # plot x and y using blue circle markers
>>> plot(y)           # plot y using x as index array 0..N-1
>>> plot(y, 'r+')     # ditto, but with red plusses

You can use `.Line2D` properties as keyword arguments for more
control on the appearance. Line properties and *fmt* can be mixed.
The following two calls yield identical results:

>>> plot(x, y, 'go--', linewidth=2, markersize=12)
>>> plot(x, y, color='green', marker='o', linestyle='dashed',
...      linewidth=2, markersize=12)

When conflicting with *fmt*, keyword arguments take precedence.


**Plotting labelled data**

There's a convenient way for plotting objects with labelled data (i.e.
data that can be accessed by index ``obj['y']``). Instead of giving
the data in *x* and *y*, you can provide the object in the *data*
parameter and just give the labels for *x* and *y*::

>>> plot('xlabel', 'ylabel', data=obj)

All indexable objects are supported. This could e.g. be a `dict`, a
`pandas.DataFame` or a structured numpy array.


**Plotting multiple sets of data**

There are various ways to plot multiple sets of data.

- The most straight forward way is just to call `plot` multiple times.
  Example:

  >>> plot(x1, y1, 'bo')
  >>> plot(x2, y2, 'go')

- Alternatively, if your data is already a 2d array, you can pass it
  directly to *x*, *y*. A separate data set will be drawn for every
  column.

  Example: an array ``a`` where the first column represents the *x*
  values and the other columns are the *y* columns::

  >>> plot(a[0], a[1:])

- The third way is to specify multiple sets of *[x]*, *y*, *[fmt]*
  groups::

  >>> plot(x1, y1, 'g^', x2, y2, 'g-')

  In this case, any additional keyword argument applies to all
  datasets. Also this syntax cannot be combined with the *data*
  parameter.

By default, each line is assigned a different style specified by a
'style cycle'. The *fmt* and line property parameters are only
necessary if you want explicit deviations from these defaults.
Alternatively, you can also change the style cycle using the
'axes.prop_cycle' rcParam.


Parameters
----------
x, y : array-like or scalar
    The horizontal / vertical coordinates of the data points.
    *x* values are optional and default to `range(len(y))`.

    Commonly, these parameters are 1D arrays.

    They can also be scalars, or two-dimensional (in that case, the
    columns represent separate data sets).

    These arguments cannot be passed as keywords.

fmt : str, optional
    A format string, e.g. 'ro' for red circles. See the *Notes*
    section for a full description of the format strings.

    Format strings are just an abbreviation for quickly setting
    basic line properties. All of these and more can also be
    controlled by keyword arguments.

    This argument cannot be passed as keyword.

data : indexable object, optional
    An object with labelled data. If given, provide the label names to
    plot in *x* and *y*.

    .. note::
        Technically there's a slight ambiguity in calls where the
        second label is a valid *fmt*. `plot('n', 'o', data=obj)`
        could be `plt(x, y)` or `plt(y, fmt)`. In such cases,
        the former interpretation is chosen, but a warning is issued.
        You may suppress the warning by adding an empty format string
        `plot('n', 'o', '', data=obj)`.

Other Parameters
----------------
scalex, scaley : bool, optional, default: True
    These parameters determined if the view limits are adapted to
    the data limits. The values are passed on to `autoscale_view`.

**kwargs : `.Line2D` properties, optional
    *kwargs* are used to specify properties like a line label (for
    auto legends), linewidth, antialiasing, marker face color.
    Example::

    >>> plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
    >>> plot([1,2,3], [1,4,9], 'rs',  label='line 2')

    If you make multiple lines with one plot command, the kwargs
    apply to all those lines.

    Here is a list of available `.Line2D` properties:

  agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
  alpha: float
  animated: bool
  antialiased or aa: bool
  clip_box: `.Bbox`
  clip_on: bool
  clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
  color or c: color
  contains: callable
  dash_capstyle: {'butt', 'round', 'projecting'}
  dash_joinstyle: {'miter', 'round', 'bevel'}
  dashes: sequence of floats (on/off ink in points) or (None, None)
  drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
  figure: `.Figure`
  fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'}
  gid: str
  in_layout: bool
  label: object
  linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
  linewidth or lw: float
  marker: marker style
  markeredgecolor or mec: color
  markeredgewidth or mew: float
  markerfacecolor or mfc: color
  markerfacecoloralt or mfcalt: color
  markersize or ms: float
  markevery: None or int or (int, int) or slice or List[int] or float or (float, float)
  path_effects: `.AbstractPathEffect`
  picker: float or callable[[Artist, Event], Tuple[bool, dict]]
  pickradius: float
  rasterized: bool or None
  sketch_params: (scale: float, length: float, randomness: float)
  snap: bool or None
  solid_capstyle: {'butt', 'round', 'projecting'}
  solid_joinstyle: {'miter', 'round', 'bevel'}
  transform: `matplotlib.transforms.Transform`
  url: str
  visible: bool
  xdata: 1D array
  ydata: 1D array
  zorder: float

Returns
-------
lines
    A list of `.Line2D` objects representing the plotted data.

See Also
--------
scatter : XY scatter plot with markers of varying size and/or color (
    sometimes also called bubble chart).

Notes
-----
**Format Strings**

A format string consists of a part for color, marker and line::

    fmt = '[marker][line][color]'

Each of them is optional. If not provided, the value from the style
cycle is used. Exception: If ``line`` is given, but no ``marker``,
the data will be a line without markers.

Other combinations such as ``[color][marker][line]`` are also
supported, but note that their parsing may be ambiguous.

**Markers**

=============    ===============================
character        description
=============    ===============================
``'.'``          point marker
``','``          pixel marker
``'o'``          circle marker
``'v'``          triangle_down marker
``'^'``          triangle_up marker
``'<'``          triangle_left marker
``'>'``          triangle_right marker
``'1'``          tri_down marker
``'2'``          tri_up marker
``'3'``          tri_left marker
``'4'``          tri_right marker
``'s'``          square marker
``'p'``          pentagon marker
``'*'``          star marker
``'h'``          hexagon1 marker
``'H'``          hexagon2 marker
``'+'``          plus marker
``'x'``          x marker
``'D'``          diamond marker
``'d'``          thin_diamond marker
``'|'``          vline marker
``'_'``          hline marker
=============    ===============================

**Line Styles**

=============    ===============================
character        description
=============    ===============================
``'-'``          solid line style
``'--'``         dashed line style
``'-.'``         dash-dot line style
``':'``          dotted line style
=============    ===============================

Example format strings::

    'b'    # blue markers with default shape
    'or'   # red circles
    '-g'   # green solid line
    '--'   # dashed line with default color
    '^k:'  # black triangle_up markers connected by a dotted line

**Colors**

The supported color abbreviations are the single letter codes

=============    ===============================
character        color
=============    ===============================
``'b'``          blue
``'g'``          green
``'r'``          red
``'c'``          cyan
``'m'``          magenta
``'y'``          yellow
``'k'``          black
``'w'``          white
=============    ===============================

and the ``'CN'`` colors that index into the default property cycle.

If the color is the only part of the format string, you can
additionally use any  `matplotlib.colors` spec, e.g. full names
(``'green'``) or hex strings (``'#008000'``).

Multiple dispatch

In an OOP language like Python or C++, given an object o, you would type o.method(x,y) to call a method, and it would choose the correct method based on the runtime ("dynamic") type of o (for a "virtual" method).

In Julia, the analogous code would call method(o, x, y)o is just one of the arguments. But Julia looks at the runtime ("dynamic") types of all the arguments to decide on the method to call.

In this sense it is a strict superset of multiple dispatch. It is not equivalent to C++ overloading, because that is static overloading. There was a nice talk about the differences between OOP, static overloading, and dynamic multiple dispatch at JuliaCon 2019 that I strongly encourage you to go watch.

In [130]:
foo(x, y) = x + y
Out[130]:
foo (generic function with 1 method)
In [131]:
foo(3, 4)
Out[131]:
7
In [132]:
foo(A, 4)
MethodError: no method matching +(::Array{Int64,2}, ::Int64)
For element-wise addition, use broadcasting with dot syntax: array .+ scalar
Closest candidates are:
  +(::Any, ::Any, !Matched::Any, !Matched::Any...) at operators.jl:538
  +(!Matched::Missing, ::Number) at missing.jl:115
  +(!Matched::BigFloat, ::Union{Int16, Int32, Int64, Int8}) at mpfr.jl:378
  ...

Stacktrace:
 [1] foo(::Array{Int64,2}, ::Int64) at ./In[130]:1
 [2] top-level scope at In[132]:1
 [3] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1091
 [4] execute_code(::String, ::String) at /Users/stevenj/.julia/dev/IJulia/src/execute_request.jl:27
 [5] execute_request(::ZMQ.Socket, ::IJulia.Msg) at /Users/stevenj/.julia/dev/IJulia/src/execute_request.jl:86
 [6] #invokelatest#1 at ./essentials.jl:710 [inlined]
 [7] invokelatest at ./essentials.jl:709 [inlined]
 [8] eventloop(::ZMQ.Socket) at /Users/stevenj/.julia/dev/IJulia/src/eventloop.jl:8
 [9] (::IJulia.var"#15#18")() at ./task.jl:356
In [133]:
foo(A::Matrix, y::Number) = A + y*I
Out[133]:
foo (generic function with 2 methods)
In [134]:
foo(A, 100)
Out[134]:
3×3 Array{Int64,2}:
 101    3    7
   4  107    2
   0    1  101
In [135]:
foo(A, A)
Out[135]:
3×3 Array{Int64,2}:
 2   6  14
 8  14   4
 0   2   2
In [ ]: