Julia: Tutorial & Code-Collection¶
Source: https://github.com/markomlikota/CodingSoftware
MIT License, © Marko Mlikota, https://markomlikota.github.io
Exercises¶
1 Introduction¶
2 Basics & Scalars¶
Exercise 2.a.i¶
Compute $33/19$ and round the result to 2 digits.
Exercise 2.a.ii¶
Define $a = 3.5$, $b = Inf$ and $c = NaN$. Check for each object whether it's finite.
Exercise 2.b.i¶
Create the complex number $z = 9 + 3im$. Store the real part and calculate it's square root
Exercise 2.b.ii¶
Write a boolean expression to test that $5$ is strictly between $3$ and $9$
Exercise 2.b.iii¶
Extend the previous exercise: add another condition to check that $5$ is also not equal to $7$.
Exercise 2.b.iv¶
Convert the string "33//19" to a rational number and add $1//4$ to it. Now convert the result to a floating number rounded to $3$ digits. Finally, create a sentence that prints your result, e.g. "The result is x".
Exercise 2.b.v¶
Install the package "Distributions".
3 Functions¶
Exercise 3.a.i¶
Write a function $fAfterInc(x)$ that increases a number by $15\%$ and returns the result rounded. Test it for $x = 100$.
Exercise 3.a.ii¶
Write a function $fProfit(revenue, cost)$ that returns both the profit ($revenue – cost$) and the profit margin ($profit / revenue$). Apply for revenue of $600$ and cost of $450$.
Exercise 3.a.iii¶
Write a function $fOut(y)$ that returns another function $fInn(x)$. The inner function should check if $x$ is bigger than $y$. Then apply $fOut$ at $y=5$ and apply the obtained $fInn$ to $x = 3$ and $x = 6$.
4 Vectors¶
Exercise 4.a.i¶
Create a vector $b$ that goes from $4$ to $44$ in steps of $8$.
Exercise 4.a.ii¶
Now multiply each element of vector $b$ by $3$ and store in a new vector.
Exercise 4.b.i¶
Let $a = (2, 4, -8, 9, -3, 8, 43, 4)'$ be a $8 \times 1$-vector.
Find the largest and smallest elements in $a$ without using maximum()
or minimum()
,
but by using max()
and min()
.
Exercise 4.b.ii¶
Let $b = (1, -4, 5, -9, 3, -8, 14, -4)$ be a vector. Define a function $fAbs(x)$ that returns absolute value of $x$ and then compute the sum of the absolute values of all elements in $b$.
Exercise 4.c.i¶
Define the vector $c = (4, 5, 2, 0, 8,10 ,-5, 16, 9, 15)$. Print out the first, last and every third element.
Exercise 4.c.ii¶
Now change the first element of $c$ to $10$, insert number $99$ in second position and multiply the first two element by $2$. Print the modified vector $c$.
Exercise 4.c.iii¶
Given the student grades $(45, 72, 88, 55, 39, 91, 60)$, print the grades from highest to lowest and then print only the passing grades ($>=60$)
Exercise 4.d.i¶
Create a vector of vectors $vva = ((1,2),(3,4))$. Make a copy $vvaa$ of it. Now, change the second element of second subvector in $vva$ to 50 and print $vvaa$. What do you observe? How can this be avioded?
Exercise 4.d.ii¶
Create a vector $b = (2, 4, 6)$. Define $bsq$ as the square of each element in $b$. Change an element of $b$ and then print $bsq$. What do you observe?
5 Matrices & Arrays¶
Exercise 5.a.i¶
Combine the vectors $b$ and $bsq$ from previous exercise into matrix $Z$. Replace the second column of $Z$ to take values $1$,$2$ and $3$.
Exercise 5.a.ii¶
Create the matrix $$ X = \begin{bmatrix} 3 & 6 & 9 \\ 4 & 8 & 19 \\ 5 & 10 & 15 \end{bmatrix} \; .$$ Find all positions of elements greater than $6$.
Exercise 5.b.i¶
You are given the matrix $$ Y = \begin{bmatrix} 2 & 1 & 0 \\ 1 & 2 & 1 \\ 0 & 1 & 2 \end{bmatrix} \; .$$ Identify the factors by which the matrix $Y$ stretches in space (eigenvalues), and the directions in which this stretching happens (eigenvectors).
Exercise 5.b.ii¶
Take the vector $S = (2, 5, 1, 4, 3, 6, 7, 0, 8)$ and transform it into a 3×3 matrix $mS$; compute the column-wise cumulative sum, then find the mean of the lower triangular part of $mS$ (including the diagonal).
Exercise 5.b.iii¶
The matrix below shows production costs over three months (rows) for two goods (columns): $$ Cost = \begin{bmatrix} 10 & 12 \\ 11 & 15 \\ 9 & 14 \end{bmatrix} \; . $$ How much does the cost of each good vary over time? Which good shows more fluctuation in costs?
Exercise 5.b.vi¶
Continuing the previous exercise: how do the costs of the two goods move together, and how closely related are they?
6 Conditionals & Loops¶
Exercise 6.a.i¶
Given vector $a = (1, 4, 5, 6, 10)$. Compute it's mean and if the mean is greater than $5$, print "High average", else print "Low average".
Exercise 6.a.ii¶
Create the matrix $$ Q = \begin{bmatrix} 1 & 0 & 3 \\ 8 & 5 & 6 \\ 9 & 1 & 9 \end{bmatrix} \; .$$ Use a nested for-loop to go through each row and column, print the position (row, column) and the element, and then also print its square.
Exercise 6.a.iii¶
Define the function $f(x) = x^2 - 10$. Start with $x=1$ and repeatedly increase $x$ by $1$ until $f(x)$ becomes larger than $50$. Print the value of $x$ when this condition is first satisfied.
7 Object-Scopes¶
Exercise 7.a.i¶
Define $s = 0$. Write a for loop that adds the numbers $1:5$ to $s$. Now write a function $fadd()$ that i) takes no arguments, ii) performs a similar loop, adding $1:7$ to $s$, and iii) returns $s$. Execute the function. What happens? Does $s$ change outside the function?
Exercise 7.a.ii¶
Adjust the function from the previous exercise so that it indeed returns the sum of $1:7$.
8 Further Object-Types¶
Exercise 8.a.i¶
Write a Julia-expression for Utility $U(x,y) = x^{0.5} y^{0.5}$. Evalutate it for $x = 4$ and $y = 9$
Exercise 8.a.ii¶
Create a vector of symbols $(:a, :b, :v)$. Write a loop that builds the expression $a1 + b2 + c3$ using the symbols and their index numbers. Lastly evaluate the expression for $a = 2, b = 3, c = 4$.
Exercise 8.a.iii¶
You are given a tuple representing a point in two-dimensional space $P = (3, 4)$. Extract the $x$ and $y$ coordinates from the tuple and compute the distance of the point from the origin $(0, 0)$. Try to change the x coordinate inside the tuple to see what happens.
Exercise 8.a.vi¶
Create a Dataframe with the given data $$\begin{array}{|c|c|c|c|} \hline \textbf{Year} & \textbf{GDP} & \textbf{Inflation} & \textbf{Unemployment} \\ \hline 2020 & 500 & 2.1 & 5.0 \\ 2021 & 550 & 1.8 & 4.7 \\ 2022 & 600 & 2.5 & 4.5 \\ \hline \end{array} $$
Print the Dataframe. Extract the column GDP and calculate it's average.
9 Path-, Folder- & Workspace-Management¶
Exercise 9.a.i¶
Create a folder called "Inputs" and, in there, write a file called params.jl
, which defines: $\mu = 50$ (mean), $\sigma = 10$ (std. deviation).
In your main/current file, load params.jl
, define a function $fZscore(x) = (x - \mu)/\sigma$ that uses the parameters from params.jl
, and print the result for $x = 70$.
Exercise 9.a.ii¶
Create a new subfolder called "Functions" inside your main working directory. Inside this folder, manually create a file called area_circle.jl
that defines the following function:
$fAreacircle(x) = \pi r^2$.
Then, in your main/current file, load area_circle.jl
and print the results of the function with $r = 5$.
10 Storing & Loading Data¶
Exercise 10.a.i¶
Define the vector $c = [3,4,6]$ and store it as a .txt-file
in your current working directory. Then, load the data from this .txt-file
to a vector $d$. Make sure your vector $d$ is actually a vector and not a matrix.
Exercise 10.a.ii¶
You are given GDP data $$ \begin{array}{|c|c|} \hline \textbf{Year} & \textbf{GDP} \\ \hline 2020 & 500 \\ 2021 & 550 \\ 2022 & 600 \\ 2023 & 520 \\ \hline \end{array} $$
Create a dataframe 'dfgdp' and save it as gdp.csv
file in your current directory. Then reload the again into a new dataframe and caculate the GDP growth from $2020$ to $2023$.
11 Random Variables¶
Exercise 11.a.i¶
Draw $1000$ random numbers from the standard normal distribution, i.e. $N \sim \mathcal{N}(0,1)$. Store them in a vector $x$. Next, compute the mean and standard deviation of your draws.
Exercise 11.a.ii¶
Generate a 4×4 matrix $R$ of Uniform random numbers with range $[0,1]$. Replace all entries greater than $0.5$ with $1$, and the rest with $0$ and print the resulting matrix.
Exercise 11.a.iii¶
Consider a Binomial distribution $B(n=10, p =0.3)$. Using pdf
and cdf
, compute the probability of exactly 4 successes and the probability of at most 4 successes. Lastly, set a loop to calculate and print the probabilities of getting $0, 1, 2, …, 10$ successes $$P(X = k), \quad k = 0,1,2,\dots,10.$$
Exercise 11.a.vi¶
You are given a bivariate normal with mean vector $v\mu = (0,0)$ and $ m\Sigma = \begin{bmatrix}1 & 0.5 \\ 0.5 & 1 \end{bmatrix} $. Fix a Random.seed
so your results are reproducible. Definie the distribution and then draw $5$ random vectors, storing them in a matrix where each row is one draw. Using this sample, compute the $2.5\%$ and $97.5\%$ quantiles for each column.
Exercise 11.a.v¶
A lottery has 6 prizes $(3, 6, 9, 12, 15, 18)$ with probabilities $(0.1, 0.05, 0.3, 0.2, 0.1, 0.25)$. Use Categorical()
to simulate one random prize.
12 Parallelization¶
Exercise 12.a.i¶
Given the function $f(k) = \sum_{i=1}^{50000} \frac{1}{i+k}$. Define the function as $fMyFun(k)$ that returns their sum. For $M = 1000$, first create a SharedArray
and fill it using a @distributed
loop. Next craete a normal array and fill it using a regular for loop. Now comparing the runtimes of the two versions, what do you observe?
Exercise 12.a.ii¶
Simulate incomes for $100,000$ people, where each income is drawn from a $LogNormal(10, 0.5)$ distribution.
Then use a multicore loop to draw the samples and fill in a SharedArray
. Finally, compute and compare the average income from your simulation with the theoretical mean. Hint: The theoretical mean of a $LogN(\mu,\sigma)$ is $e^{\mu + \tfrac{\sigma^2}{2}}$
13 Plotting¶
Exercise 13.a.i¶
Imagine an economy where GDP grows at a constant rate of $3\%$ per period i.e. $GDP_t=100×(1+0.03)^t$ for $t=1,2,…,30$. Use a loop to generate the GDP values for $30$ periods and then plot the GDP path.
Exercise 13.a.ii¶
Now suppose the GDP values from Exercise 1 correspond to monthly observations starting from 1 January 2021. Create vectors for the corresponding years and months (e.g. 2021 M1, 2021 M2, …).
Hint: you can build the labels by looping over months and resetting to M1 after M12. Lasltly, plot the GDP path against these monthly labels instead of $t$ periods.
Exercise 13.b.i¶
You want to compare different GDP paths. Start by writing a function $fMyEmptyGdp()$ which creates an empty plot with axis labels, title, etc. Use a loop to plot several GDP line paths (e.g.growth rates of $2\%$, $3\%$, and $5\%$) on the same figure.
Exercise 13.b.ii¶
Suppose a teacher collects data on $30$ students' weekly study hours and exam grades. Generate random data for study hours between 1 and 20. For exam grades assume they rise with study hours plus a little random variation (e.g. $examGrades = 40 + 2 \times studyHours + rand(-5,5,N)$). Make a scatter plot of exam grades (y-axis) against study hours (x-axis).
Exercise 13.c.i¶
Simulate 100 heights (in cm) that follows a normal distribution ~ $N(170,10)$. Plot a histogram (as a density) and overlay a kernel density curve.
Exercise 13.c.ii¶
Simulate data for four countries over $t = 24$ periods using different random distributions (one distribution per country). Make one line plot for each country and combine them into a $2×2$ layout. (Hint: You can store the distributions and titles in vectors, and use a for loop to generate the data and plots.)
Exercise 13.c.iii¶
A survey records the preferred study method for a small group of students: $$ \begin{array}{|c|c|c|c|} \hline \textbf{Gender} & \textbf{Group only} & \textbf{Individual only} & \textbf{Both} \\ \hline \text{Male} & 10 & 5 & 5 \\ \text{Female} & 6 & 8 & 6 \\ \hline \end{array} $$
Create a bar chart comparing male and female preferences side by side. Then make a pie chart showing the overall preference distribution (all students combined). Combine both plots in a $1×2$ layout.
14 Further¶
Exercise 14.a.i¶
Consider the matrix $A$ and vector $b$:
$$
A = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 1 & 6 \\ 7 & 8 & 1 \end{bmatrix} \; , \quad b = \begin{bmatrix} 1 \\ 2 \\ 2 \end{bmatrix} \; .
$$
Compare the computational time needed to solve the system of equations $Ax = b$ by typing A\b
and by typing inv(A)*b
.
Exercise 14.a.ii¶
Let $f(x) = (x-3)^2+5$. Find the value of $x$ that minimizes this function.
Exercise 14.a.iii¶
Let $g(x) = ln(x^2 +1)$. Compute the derivative at $x=1$. Then define a function $fMyGradient(x)$ that returns the gradient at any x. Plot both $f(x)$ and $f'(x)$ over the range $x \in[-2,2]$.
Exercise 14.a.iv¶
You are given $x = (1, 2, 3, 4)$ and $y = (1 , 4, 9, 16)$. Use linear interpolation to approximate the value of the function at $x = 2.5$. Now use the same object to extrapolate and approximate the value at $x = 5$.
Exercise 14.a.v¶
You are given $f(x,y) = x^2 + 3xy$. Find the partial derivatives and then evaluate $f$ at $x = 2$ and $y = 1$.