Skip to main content

Scopes in Julia

Julia is a high-level general-purpose dynamic programming language intended to address the needs of high-performance numerical analysis and computational science, without the need of separate compilation to be fast.


The region in a program where a variable is known is called the scope of the variable. A variable which can be accessed from anywhere in the program is called a top-level or global scope. A variable defined in a local scope can only be accessible from that scope.

Global and local scopes

Let's look at an example:

   # global scope
   x = 1
   # local scope
   function scopes()
       println(x) # x is a global scope and accessible
       y = 1.0    # y is local to the function scopes

Asking the julia shell to print the value of y results in an error, since it is defined in a local scope inside the function scopes and not as a global variable like x.

  julia> println(y)

  ERROR: UndefVarError: y not defined
  [1] top-level scope at none:0

for, while, try, or let

In Julia, any variable defined in a for, while, try or let block will be local unless it is used by an enclosing scope before the block.

   # example on for, while, try or let blocks
   y = 3
   for i = 1:10 #for loop is similar to the while loop
       y = i + 3
       if y == 6 #local variable inside a for-scope
	   println("The value of local y: $(y)")

However, global variables are not accessible in for and while loops as can be seen in the example below and results in a ERROR: UndefVarError: y not defined

   # inaccessible global variables in for and while loops
   y = 3
   while y < 10 #while-loop
       y += 1
       if y == 5
	   println("The value of local y: $(y)")

let blocks

To create a new local binding for a variable use the let block

    ## without let block in a for loop
    anon = Array{Any}(undef, 2)
    for i = 1:2
	anon[i] = () -> println(i)
	i += 1
    # anon function is called in julia to get

    julia> anon[1]()

    julia> anon[2]()
    ## using let block for i values to stick
    anon = Array(Any)(undef, 2)
    for i = 1:2
	let i = i
	    anon[i] = () -> println(i)
	i += 1
    # anon function is called in julia to now get
    julia> anon[1]()

    julia> anon[2]()

global and local prefix

The prefix keywords global and local can be used to decide which one you want to use if variables with same name in different scopes exist. Although, this is not a good practice as it would be harder to keep track even if Julia provides a neat way to implement such instances. A little example:

   x = 9
   function funscope(n)
       x = 0 # x is in the local scope of the function
       for i = 1:n
	   local x # x is local to the for loop
	   x = i + 1
	   if (x == 7)
	       println("This is the local x in for: $x") #> 7
       println("This is the local x in funscope: $x") #> 0
       global x = 15

Compound expressions begin…end, and conditionals if..elseif..else..end, do not introduce a local scope.

Using global scope variables should be minimized as it has an effect on the performance of the program and restricting the scope of a variable is better.

State space linearization of an inverted pendulum

Inverted pendulum

An inverted pendulum on a cart is as shown in the figure.


The system dynamics defined by Newton's second law of motion can be written as the following set of equations.

\begin{align} \ddot{p} &= \frac{\dot{\theta}^{2} m L \sin \theta-\frac{3}{4} m g \sin \theta \cos \theta+u}{M+m-\frac{3}{4} m \cos ^{2} \theta} \\ \ddot{\theta} &= \frac{\frac{3 g}{4 L}(M+m) \sin \theta-\frac{3 m}{4} \dot{\theta}^{2} \sin \theta \cos \theta-\frac{3}{4 L} u \cos \theta}{M+m-\frac{3}{4} m \cos ^{2} \theta} \end{align}

Given the dynamics, the state vector can be chosen to be the positions & velocities.

\(\mathbf{x}=\left[ \begin{array}{c}{\theta} \\ {\dot{\theta}} \\ {p} \\ {\dot{p}}\end{array}\right]=\left[ \begin{array}{c}{x_{1}} \\ {x_{2}} \\ {x_{3}} \\ {x_{4}}\end{array}\right]\)

The nonlinear state equations as functions of the states and inputs

\begin{aligned} \dot{\mathbf{x}} &=\mathbf{f}(\mathbf{x}, u) \\ y &=g(\mathbf{x}, u) \end{aligned}

can be written as,

\begin{align} \mathbf{\dot{x}} = \left[ \begin{array}{c}\dot{\theta} \\ {\ddot{\theta}} \\ \dot{p} \\ {\ddot{p}}\end{array}\right] &= \left[ \begin{array}{c}{x_{2}} \\ \frac{\frac{3 g}{4 L}(M+m) \sin x_{1}-\frac{3 m}{4} \sin x_{1} \cos x_{1} \cdot x_{2}^{2}-\frac{3}{4 L} \cos x_{1} \cdot u}{M+m-\frac{3}{4} m \cos ^{2} x_{1}} \\ x_{4} \\ \frac{m L \sin x_{1} \cdot x_{2}^{2}-\frac{3}{4} m g \sin x_{1} \cos x_{1}+u}{M+m-\frac{3}{4} m \cos ^{2} x_{1}} \end{array}\right] \\ y = p &= x_{3} \end{align}

The state equations above are description of a nonlinear system due to the sine and cosine values. The stationary state is selected as \(\mathbf{x}_{0}=\left[ \begin{array}{llll}{0} & {0} & {0} & {0}\end{array}\right]^{T}\) and these nonlinearities can be linearly approximated by assuming that \(\sin \theta \cong \theta, \cos \theta \cong 1\) and \(\dot{\theta}^{2} \cong 0\)

Substituting these values in the state equations gives,

\begin{align} \dot{x}_{2} &= \ddot{\theta} \cong \frac{\frac{3 g}{4 L}(M+m) \theta-\frac{3}{4 L} u}{M+\frac{m}{4}} \\ \dot{x}_{4} &= \ddot{p} \cong \frac{-\frac{3}{4} m g \theta+u}{M+\frac{m}{4}} \end{align}

At the stationary point calculating the Jacobian matrix, the partial derivatives of the state equations with respect to the states and inputs, will give the linearized state equation where \(\Delta\) variables are perturbation from the stationary point.

\begin{align} \dot{\Delta x} &= \left[ \begin{array}{cccc} 0 & 1 & 0 & 0 \\ \frac{3 g(M+m)}{\left(M+\frac{m}{4}\right) 4 L} & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ \frac{-\frac{3}{4} m g}{M+\frac{m}{4}} & 0 & 0 & 0 \end{array} \right] \Delta \mathbf{x}+ \left[ \begin{array}{c} 0 \\ \frac{-\frac{3}{4 L}}{M + \frac{m}{4}} \\ 0 \\ {\frac{1}{M+\frac{m}{4}}} \end{array}\right] \Delta \mathbf{u} \\ \Delta y &= \left[ \begin{array}{llll}{0} & {0} & {1} & {0}\end{array}\right] \Delta \mathbf{x} \end{align}

Bookread: Beware Of Pity

Beware Of Pity by Stefan Zweig

This has been one of the best novels I've read in a while. The main protagonist Anton Hoffmiller, an army officer, is also the narrator of the plot in this book. Reading through the raw emotions of a person falling in contempt with his compassion and finally it turning into a smoke of guilt is what burns through this book. I've thoroughly enjoyed the read and have learnt about how people in a different time felt & thought; the human things they had stuggled within societies and those that we still wrangle with today.

Bookread: Ants Among Elephants

Ants Among Elephants by Sujatha Gidla

Reading this book has given an insight into my friends' and neighbours' lives, the evolving nature of their environment which was well hidden from the experiences I've had throughout my childhood and adult life until now. Thanks to Sujatha Gidla and her beautifully presented book 'Ants Among Elephants', we can see the whole picture and not the contorted version of truth that was passed on amongst certain castes with a clear intent to undermine the views of a major set of the society we are living with. The events presented in the book reminded me of my grandfather's stories, who worked as a lecturer in various schools, which would end abrubtly leaving the people in it stranded within the listener's imagination without any moral at the end to them as I'd been used to in the various children's storybooks but the stories were all the more captivating. The author too kept me in the web of events that is her family's life beautifully knit one after another and it is hard to keep this book away for too long while reading it.

I'd always wondered what the beautiful caligraphy on the walls spelling out the letters 'CPI', 'SFI' in the streets of Hyderabad with distinct flags next to them stood for. They had been political organisations was all that was known and these intricately painted walls were their passion to their organisations. It seemed to my naive youger self that it was a waste to have so many political parties actively competing for the same positions; as almost all of the contests were won by the major political parties. But now it is clear to me and to whomsoever would read this book that the major political parties have been inadequate in solving the problems and have not only created but also perpetuated a few more.

Ants Among Elephants has been a gut wrenching read and there were several instances where it has been an answer to curious loose-ends that lingered as distinct memories but more so painful is to read through the experiences of people. This book and its author have been a compass to my values and will be to the young of India as it describes the true history of the country.

Books I've read

A challenge

This year started off in a hope to read more books than I'd ever read in one. Since not being as fast a reader as my friends, an acheivable but a good target was to complete twelve books in 12 months.

Two more months remain for this year and three books to be completed. I'm looking forward to raising the bar a bit higher the next year and onwards post about the book read as they are completed.

Now is october(month 10.) already and these are the books that I've read so far:

Title: On the move: A Life

Title: The Gene: An intimate history

Title: The Point of Vanishing: A memoir of two years in solitude

Title: The Art of Asking: How I Learned to Stop Worrying and Let People Help

Title: Whiplash: How to survive our faster future

Title: The Idea Factory: Bell Labs and the great age of American innovation

Title: So Good They Can't Ignore You

Title: The Dip: A book that teaches you when to quit(and when to stick)

Title: Do androids dream of electric sheep?

How this blog is setup

Blogging in Emacs using Nikola

This blog is setup using emacs, orgmode(part of emacs), anaconda – for virtual environment, nikola and github – for hosting your blog. This post will take you through the steps that I've followed in order to get this blog that you are currently reading up and running from an Ubuntu machine. This is part of an exercise to write more frequently on this blog inspired by Sacha's guide on how-to.

Firstly, we can find instructions to install Emacs and orgmode on their respective webpages.

Installing Anaconda

After having our emacs and orgmode setup just to your liking, move forward by installing anaconda – a virtual environment manager.

To get the latest version of anaconda distribution, see instructions on the anaconda downloads page.

After installing anaconda, create a new virtual environment by typing in the following commands in your terminal.

   # Create a virtual environment using '-n <name>', here blog.
   $ conda create -n blog python=3

Setting up Github pages

We need a place for a blog on the web. Github has an amazingly easy way to publish your website using github-pages. All we need to do is create an empty repository in your account like <username> This is going to be the address of your new blog and you can find more on how this works on github-pages.

Go through 'Github pages' part from this blog post to create one.

Installing Nikola in anaconda environment

After setting up the github page repository for your blog, install nikola so that you can publish it right from your terminal.

   # Activate the conda virtual environment 'blog' created earlier
   $ source activate blog
   # Install nikola using pip
   (blog)$ pip install --upgrade pip 'Nikola[extras]'

Using nikola and blogging

Now that we have nikola installed in anaconda virtual environment, we can start using nikola and orgmode to create our first blog post and publish it on the internet.

Just follow the above post, from 'Site creation' right through to the end to use nikola, install a theme for your blog, check if all looks good on your local machine and publish it onto your github-pages.


It would be great to activate conda virtual environment, open an orgmode buffer in emacs, write the post & publish the blog via keybindings-hook from inside of emacs once a post looks good. I've seen a couple of ways to do this and would like to implement them into my blogging setup in the future.

Blog as a Journal

This is a blog about robots, learning, algorithms, programming, control-theory, optimization along with books, movies and all my musings.