Chapter goals:

  • Learn Matlab’s layout
  • Store information as variables
  • Display information
  • Arithmetic functions

 

Introduction

Matlab has quite a lot of stuff going on when you first open it. This chapter is going to briefly go over all the important elements in setting up Matlab and orient you to the interface. 

 

Matlab interface

 

When you open Matlab for the first time you should see an interface like this. Yours might differ slightly based on what version of Matlab you have (here is 2018a) but it will have the same overall elements. Let’s go left to right, top to bottom, and go over all these panels. 

Top bar

 

Matlab Interface – Top Bar

 

At the very top of Matlab there are multiple tabs for navigating different parts of Matlab. “Home” will give you many useful options which we will get into below. “Plots” will help with graphing and “Apps” can give you an interactive interface (as opposed to programming these from scratch) to use some tools such as fitting curves to your data or analyzing various signals.

If you do not see the three other light-blue tabs, “Editor”, “Publish”, and “View”, go to your Home tab and press the “New Script” button (below image, left). Pressing this button should open a new window called “Editor” (middle panel) and the three aforementioned tabs will come up at the top. The Editor tab gives you lots of useful tools to work with your code such as creating new programs, opening existing programs, and most importantly saving what you’re working on. “Scripts” are essentially what Matlab calls computer programs. We will write code into our scripts which we can run and the computer will execute what the code says. Quick note, the “Home” tab and “Editor” tab are quite similar but differ in some ways. However, “Home” is more for controlling Matlab the program while the “Editor” tab is more useful when writing your own programs.

 

New Script
Matlab Interface – Editor

 

Matlab environment 

Moving on from the top bar we have the overall Matlab environment. If you have started a new script your should see five panels, from left the right, top to bottom: “Current Folder”, “Details”, “Editor”, “Command Window”, and “Workspace”.

Current Folder

The current folder in Matlab is very similar to how you’re used to navigating a computer’s folders and files. Starting from the top you have a backward and forward arrow to visit folders you have recently had open in Matlab. Next to those you have your “Up One Level” button which will bring you back to the folder which your current folder is in e.g. clicking it in my example below will move us from the Matlab folder to the porbl004 folder. Lastly there is the “Browse for folder” button with the green arrow which will open your computer’s normal file explorer which you may find easier to navigate to say find your data. Across the top if your current location on your computer which is open. In the window itself we can see useful information such as folder and file Names.

 

Matlab Interface – Current Folder

 

We’ll start using the Current Folder now to set ourselves up for the next Chapter. Right click in the Current Folder panel and click on “New Folder”, as you would normally to create a new folder on your computer. Right click your new folder, go to Rename, and rename it to “Chapter 1”. You’ll notice it’s all in grey and the folder is faded out. This means that Matlab knows this is a folder on your computer but that Matlab isn’t allowed to look into that folder. This is the case for nearly your whole computer: Matlab will not know where to look for folders or files on your computer unless you tell it where it is allowed to look for them. To tell Matlab where to look we need to give it a Path to follow to find our folders and files. 

 

Matlab Interface – Current Folder – New

 

Adding a folder to the path

In the next chapter we will want to work with data in our Chapter 1 folder. To do this, we need to tell Matlab it is allowed to look in the Chapter 1 folder. To do this, click the “Home” tab. On the right side of the Home tab you will see a folder icon called “Set Path” (outlined in red below). Click on “Set Path”. 

 

Matlab Interface – Set Path

 

A set path box will pop up. To add our Chapter 1 folder to Matlab’s path first click the “Add Folder…” button. This will open your computer’s normal navigator to wherever your Matlab’s Current Folder is. Next, click on your Chapter 1 folder then click the “Select Folder” button. Lastly, in the Set Path box, press “Save” then “Close”. Don’t forget to press Save! If you forget, the next time your start Matlab you will need to set the path all over again. If you look back to your Current Folder panel you’ll see the Chapter 1 folder is now a solid color and the text is black, indicating Matlab will look in that folder for programs or files.

Matlab Interface – Set Path – New Path

 

The “Details” panel in the bottom right is not so important at this stage. Later on, if you click on a Matlab program or data in your Current Folder it will display details about it. 

Editor

We’re back to the “Editor” that we brought up earlier by pressing “New Script” in the Home tab. The Editor is where we will write out code so we can make programs. Below you can see I started a script called “TestProgram.m”. Do this by selecting your Editor panel and opening the Editor tab. In the Editor tab, click “Save as…” and name your program “TestProgram”. Note, Matlab will not allow you to have spaces in your file names. For example, “Test Program.m” is not allowed. “TestProgram” or “Test_Program” are allowed. File names can only contain letters, numbers, or underscores. “.m” is Matlab’s file extension name, like Microsoft Word documents are “.doc”. 

 

Matlab Interface – Editor

 

Let’s make our first program! Make sure you have your TestProgram selected in the Editor panel (the Editor panel will be highlighted in blue). In our program we can write ourselves and other humans comments or notes. Comments will not be read by the computer and will appear green. Any text with one % (percent sign) or two %%‘s before it will be treated as a comment in Matlab and will not be ran. You can see below I have a heading comment on line 1 called Test program with two %%‘s. Followed by a second line with a normal comment, one %. Next you’ll see on line 4 that I have some real code (not a green comment). 

disp(‘Hello World!’);

The black disp is a function built into Matlab. A function is like a command, telling Matlab what to do. disp is a function short for displaying something. Generally, you will write the name of the function followed by parentheses. Within the parentheses contains the thing the function is acting on. Thus, if you want to display text in Matlab you would write the disp function followed by open parenthesis ( the text you want surround by apostrophe’s ‘ then close the parenthesis ) and finish off the line of code with a semicolon ;. Semicolons are used by Matlab to know when a line of code is finished. Don’t worry about memorizing these specifics for now.

Write out or copy+paste the display line of code into your TestProgram in the editor and press Save. Now we need to run our program on the computer. In the top bar Editor tab, press the big green “Run” arrow. 

 

Matlab Interface - Editor - Run
Matlab Interface – Editor – Run

 

Command window

You did it! You’ll notice in your Command Window, beneath your Editor, that your program called “TestProgram” ran, as indicated by the >>, and Hello World! was displayed! The Command Window is a very important part of Matlab that will tell you what Matlab is doing such as what program it is running and if it has ran into any errors. You can tell Matlab what to do directly in the Command Window. However, unlike in a script, the Command Window code has to be written one line at a time (kind of) and it is not saved anywhere. For an example of using the Command Window instead of a script program, let’s display our names. Click the Command Window so the cursor is blinking after the >> . Type in our same disp function but this time edit the contents to introduce yourself to Matlab. Make sure you use the apostrophes around your text! Once you have your line of code written, hit the Enter key on your keyboard. 

 

Matlab Interface – Command Window

 

Excellent! We can do all sorts of quick things in the Command Window such as using it as a calculator or asking for help on with how to use a function such as disp. Try it out yourself! You can use + to add, – to subtract, * to multiply, and / to divide. The >> indicates the program or code after it has been ran. Answers will be on the subsequent line without the >>. 

 

Matlab Interface – Command Window Example

 

Workspace

Last but not least we have our Workspace panel on the far right side of Matlab. The Workspace is a very useful Matlab feature that will show you all your data. For example, if you did some math in the Command Window you should see something in the Workspace called “ans”, short for answer. You’ll see ans corresponds to a value, in my case 10 since the last command I gave Matlab was 2*5. Matlab stores data in what it refers to as “variables”. For example, it saved the data to the answer of 2*5 as the variable ans

 

 

However, data does not have to be saved in ans and we can save any data as any name we wanted. Let’s write a program to introduce ourselves that uses variables and all of what we have learned so far.

Go back to the Editor and your TestProgram. Under our display ‘Hello World!’ line we will create a new variable called “age”. We will set age equal to, =, our current age. Finally, we’ll end the line with a semicolon. Press the green Run arrow. You’ll now see in the Workspace a new variable named “age” with the value you assigned it. You can check this worked by writing in the Command Window, disp(age); and the value you assigned age will be displayed.

 

 

Matlab testProgram

 

Matlab testProgram age

 

 

Now let’s get on with our introduction. We’ll bring back the line we wrote in the Command Window which displayed our name and put it on line 6 (or whichever line comes after our age variable line).

disp(‘My name is Blake’);

On the next line we’ll display our age with some text

disp(‘I am ‘,age,‘ years old’);

Your program should now look like this but with your age and name. Press Run.

 

 

Oh no! We got an error message in the Command Window. Let’s dissect this and find out why this happened. We can see that our program did start to run because we can see >> TestProgram. Furthermore, we can see both Hello World! and our name printed out, so the program got down to line 6. Then we have our error message from Matlab. It starts by telling us which function had the error, Error using disp. So we know there was a problem with the display function. On the next line Matlab tells us what caused the error to occur, ” Too many input arguments“. In layman’s terms, this means we put too many things in the parentheses of the function. Following this line, Matlab tells us the error occurred on line 7, followed by displaying what the offending code on line 7.

 

Matlab testProgram error

 

So how do we solve this error? Too many input arguments is a common error to encounter when programming in Matlab. Many functions, such as disp, expect a certain number of inputs. Inputs are separated by commas. You’ll see in our code we are giving display a total of three inputs, ‘I am ‘, age, and ‘ years old’. However, disp only accepts one input. We could instead try to combine them all into one input like so:

>> disp(‘I am age years old’);

I am age years old

It worked without an error, however, it doesn’t accomplish the goal of displaying our numerical age stored in the age variable. Rather, since age is within the apostrophes it is treated as text, not as a variable. This comes to an important lesson for Matlab and programming in general when working with text vs variables. We can differential text from variable names by using apostrophes. In Matlab, text within apostrophes is called a “String”. In other words, ‘age’ is a string of text while age is a variable name with a numerical value assigned to it. Using strings keeps us from mixing up text and variables of the same name. Matlab makes it easy to tell which is which; strings will always be in purple text while variables will always be black text.

Okay we need to combine strings with a variable in order to display our names. One way to do this is through concatenation. Concatenation is the process of linking things together. One way to do this in Matlab is to use square [brackets] around the multiple things you want to link together and combine into one thing. For our example, we would do:

>> disp([‘I am ‘,age,‘ years old’]);

I am  years old

Oh so close! You’ll notice we no longer get an error message for too many input arguments since we concatenated together out two text strings with our age variable. However, my age is… square? You age might not be square, but it will likely not be the numerical value you assigned to age. Without going into too much detail, this is caused by Matlab trying to treat the numerical value of age as text characters. However, we need to explicitly tell Matlab we want to convert the stored value of age into a string. Matlab has a function to just that num2str(). Num2str will convert a number into a text string. To use it, you just need to put the number or the variable which is assigned a numerical value, like our age , in the parenthesis after num2str.

>> disp([‘I am ‘,num2str(age),‘ years old’]);

I am 27 years old

And there we go! It works!

Now you may be asking why did we go through all this trouble of making a variable called age, converting it into a string, and concatenating it with other strings. Seems like a lot of steps when we could have just used:

disp(‘I am 27 years old’);

However, this is at the heart of programming. Say, for example, you want to give this program to someone else now. They have a different name and a different age. They would need to go through and change every instance of ‘Blake’ and ’27’ to their name and age. However, we could just store these two pieces of information as variables and call them when we needed. This way we would only need to change the variables and not have to change all the strings. Furthermore, it’s much easier to do mathematical operations on numbers than it is to do them on strings. Storing our age as a numerical value rather than a string can allow us to do useful math with it. Below I’ve modified the TestProgram to use what we have learned and added comments to let you know what each line is doing. 

testProgram complete

I hope this chapter helped you figure out all the moving parts of Matlab. Now let’s use what we’ve learned here to make our first practical program! 

Onward to Chapter 0.1
Back to Table of Contents


%% Test program
% This is a comment
age = 27; % store our age as a numerical value in a variable called age
name = ‘Blake’; % store our name as a string in a variable called name
currentYear = 2018; % store the current year


disp(‘Hello World!’);

disp([‘My name is ‘,name]); % display our name
disp([‘I am ‘,num2str(age),‘ years old’]); % display our age

% Calculate birth year
birthYear = currentYear – age; % subtract current year from age

disp([‘I was born in ‘,num2str(birthYear)]); % display birth year