Introduction

Overview:

  • Teaching: 10 mins
  • Exercises: 5 mins

Objectives:

  • Introduce users to the MATLAB GUI
  • Understand the roles of the editor, command line, workspace and working directory
  • Introduce variable types and syntax

The MATLAB GUI

MATLAB has a Graphical User Interface (GUI) which is very useful when programming; the GUI allows you to keep track of your files and variables, and also allows you to intertwine editing functions and scripts with running them. In this section we will quickly go over the important parts of the MATLAB GUI.

MATLAB GUI Screenshot

When you first load up MATLAB you will obtain a screen that looks something like this (Octave users may have a different layout, but all the components will be there). There's a lot to take in, but what's in front of you can be broken down into 5 main parts:

1) The Current Working Directory

The current working directory is (as the name suggests) the location on your computer in which MATLAB is currently working. This panel displays all the files and subfolders inside the current working directory, whilst the address of the directory itself is displayed in the bar above the pannel. In the screenshot above, we can see that my current working directory is H:/dos/samba_induction_matlab/worksheet/, and it contains one file, 01_matlab.ipynb.

We can change the current working directory using the folder buttons next to the address bar. If there is a function file or script saved in this directory, MATLAB can "see" it and will know what to do when you run those commands. As such, before you start writing or running functions and scripts, you should make sure you are in the correct working directory - otherwise you will get an error!

2) The Editor Window

This window displays any files that we are currently writing or editing. When we open a file by selecting it from the working directory panel, or when we create a new file using the toolbar, it will open here. In this window you can write scripts and functions in MATLAB syntax, save them, and then run them in the command line. MATLAB's editor is fairly smart, and is able to read it's own code and highlight errors or warnings with what's written, making writing code that much easier. It also has syntax highlighting, automatic indentation, and allows you to write comments in your code.

In the screenshot, I am currently editing one file, which I have not saved yet - notice the name Untitled2.m. Also notice the asterisk * after the name - even once you save a file and give it a proper name, an asterisk will appear after it's name if you make changes in the editor and don't save them.

3) The Command Line

We don't have to write functions or scripts to run MATLAB commands, we can simply type them directly into the command line if we want! Commands are typed out after the >> and are executed by pressing the return key. The command is immediately carried out, and any output is printed to the screen.

Generally, what you'll do is write a script in the editor, and then run this script in the command line. This way you can type all the commands you want to perform out first, and in order, then sit back and let MATLAB churn through them all!

4) Variable Workspace

This panel has a list of all the variables that we currently have defined, as well as some information about them. We can see that I have 3 variables currently defined; there's a $60\times60$ matrix A of numbers - the word "double" refers to "double-precision floating point number" and tells us what type of variable the matrix stores. There's also a $1\times50$ vector called b, again of numbers, and mu0 which is a constant. There are other data types besides numbers in MATLAB, the most notable being strings, but we won't go into detail about those yet.

Note that if a variable isn't in the workspace, then MATLAB doesn't know what it is!

5) Toolbar

This bar contains a number of useful features the suppliment the editor window. You can highlight a section of code to comment it out, create new files with the syntax pre-written, and automatically indent your code. You can even run subsections of your code if you're careful!

MATLAB Variables

Let's start off by looking at defining variables in MATLAB. A variable is just a name for a value that we want to store. To create a variable, we simply pick a name for it, and use the = key to give it a value. For example, let's create the variable number_ducks and give it a value by running the following command in the command line:

In [1]:
number_ducks = 10
number_ducks =  10

You should notice two things. Firstly, the workspace variables panel suddenly gets a new entry corresponding to the variable you just defined. Secondly, notice that the text number_ducks = 10 is printed to the command line. This is because whenever we set (or change) the value of a variable, MATLAB by default displays the new value to the screen. We can prevent MATLAB from doing this using a semicolon (;) at the end of the line:

In [2]:
number_ducks = 15;

Notice now that the value of number_ducks has changed in the workspace variables panel, but the new value wasn't printed in the command line.

Let's now define a few more variables:

In [3]:
yearly_cost_per_duck = 24.96;
yearly_duck_cost = number_ducks * yearly_cost_per_duck;
disp(yearly_duck_cost)
 374.40

Notice how we can define variables using the variables we currently have. But what happens if we, say, were to aquire another duck? We can add one to the variable storing the number of ducks we have like so:

In [4]:
number_ducks = number_ducks + 1;
disp(number_ducks)
 16

This highlights an important feature of = in that it takes the value on the right, then stores it in the variable on the left. Namely, before we ran the previous command, number_ducks = 15. So when we add one, we get 16. Then, we take the value 16 and store it in the variable number_ducks, overwritting the previous value.

But our yearly_duck_cost hasn't updated to take account of this new value:

In [5]:
disp(yearly_duck_cost)
 374.40

Even though we set the value of yearly_duck_cost using number_ducks, MATLAB doesn't go back and update the value of yearly_duck_cost when we change the value of number_ducks. We need to do that ourselves...

In [6]:
yearly_duck_cost = number_ducks * yearly_cost_per_duck;
disp(yearly_duck_cost)
 399.36

A better way to print variables

The last thing we should talk about is how to display variables in specific formats. You may have noticed that disp isn't very informative when you print to the screen - or you might want to print lots of values to the screen, heck even add words to the printout. To do this, we need to use the fprintf function, and provide a format specifier or print format. By way of example:

In [7]:
fprintf('I own %d ducks and they cost me £ %.2f per year \n', number_ducks, yearly_duck_cost)
I own 16 ducks and they cost me £ 399.36 per year 

What's going on here? Well, fprintf works slightly differently to disp: rather than just giving fprintf a variable name, we give it a string - we can define a string using ' marks. In this case, we have given it the string 'I own %d ducks and they cost me £ %.2f per year \n'. Now within this string, everywhere we want to print a variable we put in a % sign followed by a combination of letters and numbers - these are the format specifiers mentioned earlier. The combinations of symbols let MATLAB know how we want our variables to be displayed; the allowed formats are:

Specifier Format Name Print Output Use on
%d decimal integer number integers
%f float decimal number floats, when we don't need scientific notation
%e scientific decimal number floats, when we need scientific notation
%.n, n$\in\mathbb{N}$ precision decimal to n d.p. floats

Variable Types

MATLAB and other programming languages use particular terms for the values stored in variables. Simplistically, a float is a number that is stored in the computer memory as a decimal, an int an integer, and char (character) or str to a string.

You can mix precision specifiers with scientific and float specifiers too, by putting the letter f or e after the number of decimal points.

With this in mind, we can now interpret what fprintf('I own %d ducks and they cost me £ %.2f per year \n', number_ducks, yearly_duck_cost) is doing.

  • The string lets MATLAB know the message to print to the screen, and the format specifiers how we want the variables to be printed.
  • After the string, we put in the variables we want printed, in the order they appear, and separate them by commas.
  • When the command runs, MATLAB inserts the values of the variables into the places where we have provided a format specifier.
  • NOTE: The \n part of the string just tells MATLAB to print a new line.

    MATLAB then replaces %d with 16 (the value of number_ducks) and %.2f with 399.36 (yearly_duck_cost to 2 decimal places), and prints the result.

We can also define variables using scientific notation, and then print them to the screen in a similar way:

In [8]:
swallow_strouhal_constant = 3e0;
wing_flap_frequency = 1.5e1;
meters_per_flap = 2.2e-1;

air_speed_velocity = swallow_strouhal_constant * wing_flap_frequency * meters_per_flap;

fprintf('The air-speed velocity of an unladen swallow is %.1e ms^-1 \n',air_speed_velocity)
fprintf('A European swallow or an African swallow? \n')
The air-speed velocity of an unladen swallow is 9.9e+00 ms^-1 
A European swallow or an African swallow? 

So you think you know your variables?

Read the code that follows and predict the exact output of each of the fprintf statements that it involves.

mallard_mass = 12;
earth_mass = 5.972e24;
mallard_population_2017 = 4.73e6;
mallard_population_2016 = 4.84e6;
pop_change = mallard_population_2017 - mallard_population_2016;

fprintf('Mallard pop. in 2017 was estimated to be %.2e \n', mallard_population_2017)
fprintf('Mallard pop. in 2016 was estimated to be %f, meaning there was an estimated change of %d mallards \n', mallard_population_2016, pop_change)

fprintf('In 2017, the mass of the global population of mallard ducks was %.2e percent of the mass of the Earth \n', mallard_mass*mallard_population_2017/earth_mass)

Note: you can perform calculations with variables inside a call to fprintf, and it will print the value of the expression you put in!

Solution

Key Points:

MATLAB GUI:

  • The current working directory is the location on your computer in which MATLAB is working.
  • The editor window is used to write MATLAB functions and files, which are then run in the command line.
  • The workspace variables panel lists all the variables currently in the workspace.

Variables:

  • We assign values to variables using =
  • We can display variables using disp or fprintf