INFORMATION REPOSITORY

01. Introduction to Matlab

Updated on February 7, 2025
This first tutorial will focus on the introduction of MATLAB. With this we will delve into the general use of MATLAB, the creation and use of variables, matrixes and functions, and what you need to do when you get stuck.

Learning Goals #

  • Understand the advantages of programming compared to spreadsheet operators.
  • Conduct simple calculations in MATLAB.
  • Work with variables and matrixes. 

1. Introduction to MATLAB #

1.1. Why programming? #

A question frequently asked to us is why we would use programming instead of a tool such as Excel. This is of course a very valid question. Excel is an excellent, established and accessible tool that can be found on most computers. For the average analytical scientists it is very likely that the person is familiar with this program. We also use such programs for some of our work.

Figure 1. Overview of a selection of advantages and disadvantages that compare Excel to programming languages.

However, for analytical chemistry there are a number of reasons why it is worthwhile to invest in cultivating some programming skills. Programming languages offer tons of advantages.

1.2. Overview of MATLAB #

Let’s move on to the MATLAB interface. After you have downloaded and installed MATLAB, you will see the following window (Figure 2). This window will comprise of several components that may be displayed differently in your case.

Figure 2. MATLAB interface.

First, there is the Current Folder window (A), which is used to show the folder in which you are working as well as other folders located in this folder. Generally, MATLAB will exclusively be able to work with files located in your Current Folder. It therefore makes sense to assign a dedicated folder on your computer.

Secondly, there is the Editor window (B), which is used to write scripts as well as save and open existing scripts. It may be the case that this window is missing as you have not begun writing anything yet. Don’t worry about this for now. It is also possible that this window is external. On the bottom we have the Command Window (C), which we also often refer to as the terminal. We use this window to execute the code that we write and will be able to see the result that is returned to us. Lastly, there is the Workspace (D), which will display all the currently saved variables and allows you to interact with them.
PRACTICE MAKES PERFECT

In these tutorials we will frequently show examples of MATLAB code. You should immediately try these out and see what happens. You will feel comfortable with MATLAB even more if you explore and start to change our values to see what happens. You cannot break your computer by exploring MATLAB, so the more you play with it the better!

2. Variables & Operations #

2.1. Operations #

Let’s start with working with the program and practice some simple commands. First, enter the following code and press Enter to execute it.

				
					a = 1
				
			

Upon executing the above code, MATLAB will return the following

				
					a =

        1
				
			

We can see that MATLAB has assigned the value 1 to the variable that we have named “a”. In essence, we can store any information in a variable, and we can make as many variables as we want.

WORKING WITH OUR CODE

Note that when we place code on this page in our lessons, the first number is the line number, which is not part of your code. Also note that there is a Copy button while hovering the code block that allows you to quickly copy and paste the code.

Now, also execute the following:

				
					b = 2
c = a + b
				
			

We can see that – without us having assigned the value to it – MATLAB returns 3 as value for c. As you can see, you can name any variable as you wish.

Table 1. Overview of common mathematical operations in MATLAB.
Operation Expression
Addition
x + y
Subtraction
x – y
Multiplication
x * y
Division
x / y
Inverse division
x \ y (equivalent to y/x)
Power
x ^ y
Square root
sqrt(x)
EXERCISE 1

Create two new variables with creative names and then try out each of the operations in Table 1.

OVERWRITING FUNCTION NAMES

MATLAB is equipped with tons of functions, such as sqrt() as we have seen in Table 1. If you create a variable with the same name as the function, then the function will cease to exist until you restart MATLAB. Therefore, keep variable names simple and logical. As you progress through the course you’ll be able to better gauge what to avoid.

2.2. Vectors and matrices #

It happens continuously that we want to store several values in a single variable. For example, maybe we have a series (or array) of measurement results, or simple the entire chromatogram. We therefore need to talk about the terminology here and introduce some new concepts. Our variables can have different dimensionalities, or tensor orders, as is also shown by Figure 3.

Figure 3. The dimensionality (tensor order) of the data depends on the order of the instrument. The tensor order strongly affects data processing strategies.

Single values are zero-order tensors, whereas one-dimensional series of values are first-order tensors. Such a series is also known as a vector. A second-order tensor is a matrix, and third-order tensors are blocks.

Figure 4. Expression of a row vector, column vector and a matrix.

Important for us is that a vector can be expressed in different ways. This is illustrated in Figure 4. A row vector is a horizontal 1 x m array

				
					row_vector = [1 2 3]
				
			

yielding

				
					row_vector =

     1     2     3

				
			

Note how we use brackets to indicate that we are designing a vector. In contrast, a column vector is a vertical n x 1 array. 

				
					column_vector = [1; 2; 3]
				
			

resulting in

				
					column_vector =

     1
     2
     3
				
			

Here, we use the semicolon to indicate that the next value belongs to the new row. 

EXERCISE 2

A new method is developed by Lab A for the determination of a new performance-enhancing drug in urine. The obtained results are 5.8, 4.9, 4.7, 4.5, 5.0, 5.2, 5.6, 4.8, 5.5 and 5.1. Fill the data of Lab A into MATLAB. Try it both with the Command Window as well as your script.

When you have more data, a matrix will likely be a better expression for your data. An n x m matrix has n rows and m columns.

				
					example_matrix = [1 2 3 4; 5 6 7 8; 9 10 11 12]
				
			
				
					example_matrix =

     1     2     3     4
     5     6     7     8
     9    10    11    12
				
			
EXERCISE 3

A validation procedure is started for the method from Exercise 2, and three additional labs measure the different samples. Lab B finds 2.9, 3.0, 2.7, 2.8, 3.1, 3.0, 3.1, 3.3, 2.8 and 3.0, whereas Lab C finds 1.8, 2.0, 2.1, 2.2, 1.6, 1.6, 1.3, 1.4, 1.9 and 1.8. Finally, Lab D finds 3.9, 4.1, 4.5, 4.2, 4.7, 4.0, 4.5, 4.6, 4.4 and 4.3. Fill the data from all four labs into a single variable. Hint: You need to create a matrix.

Placing all these values was a lot of work, huh? Don’t worry, we’ll learn how to load files with large amounts of data into MATLAB in future tutorials.

2.3. Indexing #

We have now entered our first matrix into MATLAB! But how do we access the information stored in this matrix? This is done by indexing. Indexing refers to selecting specific values in a variable. Let’s take a fictive 3×4 matrix as shown in Figure 5A. This matrix features 3 rows and 4 columns. We now need to select 2 different values, which are indicated in pink.

Figure 5. Examples of indexing in a matrix.

For example, we can select a value in a matrix through

				
					result = example_matrix(2,3)
				
			
Here, we selected the third value from the second row. Note how we used this opportunity to store the result in the variable named “result”. It is also possible to select one or multiple rows or columns. For example:
				
					result = example_matrix(:,3);
				
			
In this example, all rows “:” were selected for column number 3. Note by placing a semicolon “;” behind the line, MATLAB no longer outputs us the result: the output is suppressed. But if we look at the Workspace, we can still see that result contains the column vector of column 3.
EXERCISE 4

Practice with indexing. Use the matrix that you have created during the previous exercise.

  1. Divide the 2nd value from Lab B by the 8th value from Lab D.
  2. Calculate the square root of the 5th value of Lab A.

Subtract all values of Lab C from Lab D, and divide the 9th value of the result vector through the 5th value of Lab A. If needed, round your answer to 1 decimal.  

3. Functions #

3.1. Using functions #

Now that we know how to enter and work with vectors and matrices, as well as can access information stored in them, let’s see if we can use this to our advantage.

MATLAB had a lot of built-in features, such as functions. These functions can be regarded as tools in a toolkit that can be used to perform various mathematical actions. Think about simple operations such as computing the mean of a vector, processing a signal from a chromatogram, but also imagine running an ANOVA with just a few lines of code.

Figure 6. Composition of a function line.

Let’s start simple: a general function is composed of an output, the function name and input variables (often referred to as input arguments) which are needed to run the function. To apply this, make the following exercise.

EXERCISE 6

Calculate the mean of Lab C using indexing and the matrix from earlier exercises. Hint: Use the mean() function.

To help you

				
					matrix_mean = mean(example_matrix(:,3))
				
			

The mean() function is just one of the more simple functions. There are also function which offer the user to specify further optional input, such as the dimension of a matrix over which the mean should be calculated. These optional inputs are called kwargs (KeyWord Arguments). 

3.2. Getting help #

Of course, it is difficult to guess the input arguments or kwargs of a function that we did not use before. MATLAB therefore offers the help and doc functions to help you.

To use the help function, you write “help function name”. For example

				
					help mean
				
			

yields

				
					mean   Average or mean value.
    S = mean(X) is the mean value of the elements in X if X is a vector. 
    For matrices, S is a row vector containing the mean value of each 
    column. 
    For N-D arrays, S is the mean value of the elements along the first 
    array dimension whose size does not equal 1.
 
    mean(X,"all") is the mean of all elements in X.
 
    mean(X,DIM) takes the mean along the dimension DIM of X.
 
    mean(X,VECDIM) operates on the dimensions specified in the vector 
    VECDIM. For example, mean(X,[1 2]) operates on the elements contained
    in the first and second dimensions of X.
 
    S = mean(...,OUTTYPE) specifies the type in which the mean is performed, 
    and the type of S. Available options are:
 
    "double"    -  S has class double for any input X
    "native"    -  S has the same class as X
    "default"   -  If X is floating point, that is double or single,
                   S has the same class as X. If X is not floating point, 
                   S has class double.
    Example:
        X = [1 2 3; 3 3 6; 4 6 8; 4 7 7]
        mean(X,1)
        mean(X,2)
				
			

This was only a selection, but you can already see that there is an extensive information package. 

MATLAB also offers an extensive documentation repository, which you can access by writing “doc function_name”. For example:

				
					doc mean
				
			

This will prompt a window with extensive information along with a range of examples with example data. Aside from the additional examples, the information is also laid out in a structured way.

USE THE HELP AND DOC FUNCTIONS

Explaining how all functions work in detail would make these tutorials extremely lengthy. We therefore assume from now on that you use these facilities to learn more about how to use functions. Using a programming language means that you will need to do this a lot.

EXERCISE 7

Obtain the means of all individual labs using the data matrix and a single use of the mean() function. You are only allowed to use the mean() function once! Use the help and doc functions to find out how.

4. Troubleshooting #

We have done some basic MATLAB exercises, and began our MATLAB journey. However, at some point you will encounter errors and weird outputs. Perhaps you made a typo, or you used a function wrong.

For example, if we use our above example_matrix by indexing a number that didn’t exist, then we obtain:

				
					example_matrix(6,:)
				
			
				
					Index in position 1 exceeds array bounds. 
Index must not exceed 3.
				
			

Or if we used a variable that did not exist yet:

				
					apples
				
			
				
					Unrecognized function or variable 'apples'.
				
			

4.1. General advice for coding #

  1. Frequently check if the outcome is meeting your expectations. For example, whether your calculation yields the expected output and dimensions.
  2. Google is your friend! When you do not know how to do something, Google it: “MATLAB how to calculate mean of each row of a matrix”. Every programmer does it.
  3. MATLAB is designed in a way that most of the errors will give you advice on how to solve them. Therefore, when you encounter an error, read the important part, and if you still do not understand: use the advice above! 

For more information also look at the MATLAB website. Here you can find even more information about how to work with everything from matrices to different functions, and so much more.

https://nl.mathworks.com/products/matlab.html

Concluding remarks #

We have made huge steps already in these first hours of using MATLAB. From here on, it will only get easier. Now that we know how to use the program, we can start exploring what other powerful tools exist in the toolkit. This, as well as learning about other concepts, will be topics of further tutorials. 

Is this article useful?