Learning Julia, a Python + R alternative

Julia

URLS

  1. https://next.juliabox.com/ - Contains tutorials in jupyter notebook, to execute and learning.
  2. https://www.youtube.com/watch?v=4igzy3bGVkQ

Language Basics

  1. Print variables == println(“text to print”)
  2. See documentation for a particular internal function, prepend function with ? . E.g. ?isapprox
  3. No need to declare variables before. No need to declare variable type. function typeof(variable) will figure out the type for us.
    myAnswer = 64
    typeof(myAnswer)                  — Answer = Int64
    my_pi = 3.1415
    typeof(my_pi)                         — Answer = Float64
  4. Types – Int64, Float64, String, Char, Bool (true,false)
  5. Comments using the # (for single line) or #= …. =# for multiline comments
  6. Same math operations as pythons (+ – * / %). Only difference, power in python **, in Julia it is ^
  7. Julia also has an isapprox function to compare two float values – which may NOT be equal due to conversion errors.
  8. If you need strings with double quotes ” embedded in the string, enclose it in “”" (3 double-quotes ) , instead of just 1 “
  9. You CANNOT use Single quotes for strings. It is only for characters. (like C, unlike python)
  10. Embed variables (of any type) in a string, use the $var_name syntax.
    age=30
    str=”Your age is $age years”
  11. Concat strings using 3 ways
    1. Using a function string() as string(str1,str2,str3….as many separated by commas) . Returns a concat string. Can also be used to concat or convert non-strings to strings.
    2. Use the * operator.  bigstr = str1 * str2 * str3
    3. Enclose in double quotes.  bigstr = “$str1$str2$str3″
  12. Data structures — Dictionaries, Tuples and Arrays (just like Python)
  13. Julia is 1 indexed … not 0 indexed.
  14. Create Dictionaries
    1. using the “Dict” keyword, dictVar = Dict(“key1″ => “value2″, “key2″ => “value2″)
    2. Add to existing Dict using square brackets – dictVar["key3"] = “value3″
    3. Access a value for a key using square brackets. found_value = dictVar["key3"]
    4. pop! to delete a key entry AND return the value. pop!(dictVar,”key3″)
    5. Dict are not ordered, so you cannot index into a dict
  15. Create Tuples
    1. using the round brackets tupVar = (“tval1″,”tval2″,”tval3)
    2. Tuples are immutables, so once created a tuple value at an index cannot be changed.
      1. Question: Can we add a new index to the Tuples structure?
    3. Access tuple entry using index. found_tup = tupVal[1]
      1. Remember, Julia is 1 indexed, not 0 indexed.
  16. Create Arrays
    1. using square brackets arrVar = ["aval1","aval2","aval3"]
    2. Arrays do not have to all strings or all integers, can be a mix.
      1. Question? What about for dict and tuples?
    3. Access index entry using index. found_arr = arrVal[1]
    4. Add to end of array using the push! – push!(arrVal,”aval4″)
    5. Remove last element and return it from array using pop! — pop!(arrVal).
  17. Create a simple array list variable, with increment.   listvar = firstval:increment:lastval
    N = 1:0.1:5     # Creates a list 1.0 1.1 1.2 1.3 1.4 …… 4.9  5.0
  18. Length of a datastructure using the length() function.
  19. Create Multidimensional arrays
    1. Using square brackets within square brackets. mvarray = [["av11","av12","av13"],["av21","av22"],["av31"]]
    2. Each row can have different array lengths
    3. Access each cell by square brackets separated by commas, [rowNum,colNum]
    4. NOTE — assigning using = two arrays is just copying the references to variables, pointing to the ONE SINGLE array. Changing one – with also affect the other. If you want a real copy, use the “copy()” function.  C = copy(A).
  20. Using rand() function to create 1,2,3 (or more) dimension arrays with random numbers between 0 and 1. rand(num_rows,num_columns)
  21. If you want rand() to provide random numbers from a list, provide that as a first argument.
    N = [i for i in 1:10]       # Generate an array from 1 to 10 … not 0 to 9.
    rand(N,3)           # Generate 3 random  numbers using numbers from N list
    or just
    rand(1:10,3)      # Generate 3 random  numbers using numbers from 1 to 10
  22. Use zeros() function to create 1,2,3 (or more) dimension arrays with 0 in each cell.
  23. Loops types = while and for . Use “end” keyword to end
  24. n = 1
    while n < 10
    printfln(n)
    n += 1
    end
  25. for n in 1:10
    println(n)
    end
  26. Use “for” to iterate over an array
    for aval in arrVar
    println (aval)
    end
  27. Combine two for loops into one
    val = rand(10,10)
    sum_total = 0
    for i in 1:10
    for j in 1:10
    sum_total += val[i,j]
    end
    end

    for i in 1:10, j in 1:10
    sum_total += val[i,j]
    end

  28. Julian way to create an addition MV table. Create a 10,10 table with each cell value as (rowNum+colNum).
    C = [i + j for i in 1:10, j in 1:10]

    Same in a for loop
    C = zeros(10,10)
    for i in 1:10, j in 1:10
    C(i,j) = i + j
    end

  29. Conditionals —- if …. elseif ….. else ….. end
  30. Can use the C style single line if —– (condition) ? (if true) : (if false)
  31. Use && to test condition and exec next statement only if true. (x > y) && println(“x greater than y”)
  32. Boolean operators < > == != && ||
  33. Functions created using function keyword and terminate with end keyword. function sfunc(somevar) …. end
  34. Call by just calling the function name. sfunc(123)
  35. You can just declare a function on a single line. funcName(var1,var2) = statement with $var1 and $var2. Then call function as before —- funcName(10,20)
  36. Anonymous functions – functions without a function name. Define with one or more variable names, followed by -> followed by function body. Return into a “function variable”
    fret = name,age -> println(“My Name is $name, and age is $age)
    fret(“julia”,20)

    1. Anonymous functions are also referred to as Lambda functions.
  37. Remember, variable types are not declared anywhere. So you can pass an integer to a function, which you originally created to accept a string. If Julia can translate and use it, it will. This is even true for single or MV dimensional arrays as arguments. However, in some cases, this could cause an error.
  38. Functions normally do not alter or mutate the input passed arguments. However, in case of functions that do – the convention is to append them with ! . example sort(v) vs sort!(v)
  39. If you want to be explicit on the type of a variable when defining a function, use syntax —- function f(var::String) ………. println(“Printing $var”) …… end
  40. Function Broadcasting. Typically useful when the argument passed to the function is an array. Any function can be converted to a broadcasting function by appending a period (.) after function name when call the function. In case of broadcasting, the function is “applied to every cell of the array” instead of the normal operation, where the function is applied to the entire array treated as a single argument.
    f(x) = (x * x)  # First define a one line function f(x)
    A = [i + j for i in 1:3, j in 1:2]   # Next we create a single 3×2 matrix with 1,2,3,4,5,6
    f(A)   # first we call it as a normal f(A). This will be an error because you cannot multiply a 3×2 with another 3×2 matrix (2nd has to be 2 x 3).
    f.(A) # But, this will work and just return a 3×2 matrix with each cell squared.

    1. For broadcasting, the array can be any dimension, the function will simply be executed for each cell.
  41. Packages. Available at https://pkg.julialang.org or https://luliaobserver.com
  42. Always start every Julia program with “using Pkg” so you can add/include packages later.
  43. Packages called in tutorial – Colors,
  44. Include a package using the command —- Pkg.add(“package_name”). This needs to done only once in a julia session. However, every “julia” file you wanna use the package, include the using keyword —- using package_name (note – no double quotes).
    1. Question: Can you call <pkg_name>::<pkg_function> is you dont wanna include using keyword? — NOPE. Have to use “using <pkg_name>”
  45. Basic Plotting. You can access libraries from other languages in Julia. So, you can easily use pyplot (from python).
  46. Plots.jl is included with Julia.
  47. Seamlessly use different backends without having to change commands. Available backends = gr() and plotlyjs().
  48. Commands
    gr()          # To start the backend
    plot(xvalues, yvalues, label=”plot_label”)         # Create a line plot using the x,y points
    scatter!(xvalues, yvalues, labels=”plot_points”)      # Create a scatter plot using same x,y points. Because we are calling scatter with a ! , it will overlay the scatter points in the “plot” itself. Without the ! – the scatter would replace the previous line plot().
  49. So, plot functions used – xlabel!() ylabel!() title!() xflip!() ….. note the ! so it modifies the last plot, rather than create a new one.
  50. To create a plot with multiple plots, create individual plots and assign to variables. Then call plot with these variables with the layout=(rows,cols) as 2nd argument.
    p1 = plot(x,x)
    p2 = plot(x,x.^2)
    p3 = plot (x, x.^3)
    p4 = plot (x, x.^4)
    plot (p1,p2,p3,p4,layout=(2,2),legend=false)
  51. Multiple Dispatch – multiple functions with the same name, different argument and different argument types. Julia uses the arguments to properly dispatch to arguments to the correct method.
    1. @which (expression) returns the exact method that Julia will dispatch to to execute this expression.
    2. You can “extend” an operator or function, by explicitly redefining the function with the arguments with explicit argument types using the :: (… f(x::Float64) )
  52. Basic Linear Algebra – This is very interesting. Methods to solve linear algebra equations using Matrices. Need to understand it much more.
  53. BenchmarkTools is a package that allows you to easily benchmark your program
  54. To use python packages, you import package Conda. Then you use pyimport to import the python package. Need to investigate this more.

Leave a Reply