INFORMATION REPOSITORY

03. Flow Control and Plotting

Updated on February 7, 2025
Now that we know how to open datafiles we can focus more on methods to use and display them. Typically, scripts need to be sufficiently versatile to adapt to specific characteristics of a dataset. During the third tutorial we will learn some key methods to  plotting your imported data, as we’ll learn about flow control.

Learning Goals #

  • Plot your data using a line plot, histogram or scatterplot.
  • Control the execution of your scripts using guiding statements that determine which parts of your code are activated.

1. Plotting & creating data #

In the previous tutorial we focussed on opening csv-files. We now know how to acces this data. But what if we want to visualise it? In this part, we will learn some of the most common ways to plot data. If you want more information about plotting in MATLAB you can click on this LINK.

1.1. Creating data #

If there is one benefit of being a programmer (yes, you may now call yourself one), then it is the capability of being able to quickly generating data to test your latest developments. Almost like magic, really.

For example, we already know what a vector is from Tutorial 1, but we can actually quickly generate one. Try the following:

				
					xdata   = 1:10;
				
			

For example, we already know what a vector is from Tutorial 1, but we can actually quickly generate one. Indeed, this creates a vector of 10 values. By standard the step size is the smallest integer: 1. You can also control it. For example:

				
					xdata   = 1:0.1:10;
				
			

Note, that we now do not get 100 values, but 91. This is because we started the vector at 1, to then be increased with steps of 0.1 until we reach 10.

To visualise different types of plots, it is also often useful to generate random data. Let’s create a vector containing 10 random values, between 1 and 5. Make sure to type this in a script, as we will be using these values for most op the plots.

				
					xdata   = 1:10;
ydata   = 5 * rand(10, 1);
				
			

As you can see, we are using the rand() function to create random values. This function generates values between 0 and 1. The first input argument, determines the number of rows, and the second the number of columns. By keeping the second to 1, we create a vector instead of a matrix.

EXERCISE 1

Lets make sure we understand what is going on.

  1. Inspect the functionality of the rand() function using the doc or help function.
  2. Generate an xdata vector from 1 to 100 with steps of 1.
  3. Generate an ydata vector populated with random numbers between 0 and 10. The vector should be 100 values long.
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.

1.2. Lineplot #

Now that we have a signal, let’s graphically plot it. We will continue with the data from the last part of Exercise 1. To be sure, this is how you could generate it: 

				
					xdata   = 1:100;
ydata   = 10 * rand(100, 1);
				
			

The most general plot is a line plot. This plot will connect all the implemented points with a line. Try and run the next lines of code in your MATLAB script. When running this, a new window will appear which will show the plot.

				
					% Lineplot
plot(xdata, ydata);
				
			

As you might have noticed, this plot does not portray any information about what is being plotted. So let’s add a titleaxis labels and a legend.

When at some point you are unsure on the use of the different attributes of a plot, use the help function. This will give you information on how to add attributes like titles, axis labels and legends.

				
					% Lineplot
plot(xdata, ydata);

% Title
title('Generaring random data');

% Axis labels
xlabel('xlabel');
ylabel('random values');

% Legend
legend('line plot');
				
			
Figure 1. Randomly plotted 100 values, using a lineplot.

1.3. Targeting specific figures #

Note that by merely using the plot function a window popped up. It is easy to get lost after creating several plots during a session. You can therefore also exercise control over which window is used. Let’s first create two separate figures to demonstrate this.

				
					% Creating Two Figures
figure
MyPlot1 = axes

figure
MyPlot2 = axes
				
			

The figure command immediately creates a new figure. Normally, MATLAB will always plot data in the latest figure that was called. But in this case, we have created an axes type variable and assigned for each figure a unique name (MyPlot1 and MyPlot2). Note that in the code above, the MyPlot1 = axes is applied to the latest figure that was opened.

We can now direct a specific plot, to a specific figure using, for example:

				
					
plot(MyPlot1,xdata,ydata)
				
			

1.4. Overlays #

It is also possible to create overlays of figures. Let’s create a second signal:

				
					ydata2   = 2 * rand(100, 1);
				
			

We can now plot the earlier data first and then use the hold function to prevent data to be overwritten such as is the case here

				
					% Lineplot
figure
plot(xdata, ydata);
hold on
plot(xdata2, ydata);
				
			

If you do want to overwrite the previous data, simply reverse the hold by

				
					hold off
				
			

1.5. Scatterplot and histogram #

There are other ways in which we can visualize the data better, maybe we can try a scatter plot and a histogram. The scatter plot works similar to the line plot. 

				
					% Scatterplot
scatter(xdata, ydata);

% Title
title('Generaring random data');

% Axis labels
xlabel('xlabel');
ylabel('random values');

% Legend
legend('scatter plot');
				
			
Figure 2. Scatter plot of 100 randomly generated values.

The histogram needs another input, instead of an x-axis, we need to specify the number of bins needed for the data.

				
					% Histogram
histrogram(ydata, 25);

% Title
title('Generaring random data');

% Axis labels
xlabel('xlabel');
ylabel('random values');

% Legend
legend('Histogram');
				
			
Figure 3. Histogram plot of 100 randomly generated values.

These are just some examples of plot functions, as mentioned in the beginnen you can plot almost anything in any way.  Besides changing the type of plot, you can also change the color, line thickness and a lot of other things.

EXERCISE 2

In the beginning of this tutorial we made a line plot. In this exercise we are going to personalize the plot.

  1. Change the colour of the line for one of your plots.
  2. Also change the thickness of the line.
  3. Look if you can think of any other ways you can change the appearance of this plot. 

2. Flow control #

Flow control in programming is like giving conditional instructions to a robot. You tell it to make decisions using if (e.g., if it’s sunny, go left), and handle choices with else (e.g., if you find a key, pick it up; else, keep looking). It’s all about deciding what to do next based on rules, just like following steps in a game or recipe.

To demonstrate this, we’ll make a simple if-statement based on a flow-chart. We want to make a simple script which will decide if it’s time for coffee. Imagine you have had about four cups of coffee today so far.

Figure 4. Flow chart to decide if it is time for coffee (Part 1).

To put this into a script, we must first create variables to allow the checks needed for the if-statement. Imagine you have had 4 cups of coffee so far, and are not tired. In this situation we will set the number of cups to 4, and a tired-status variable to false.

				
					% Variables
cups            = 4;
Tired           = false;

% If-Statement
if Tired == true
    disp("Get coffee");
else
    disp("No coffee for you");
end
				
			

To make the actual test for this if-statement we used == to check if Tired was equal to true. This is one way we can do a conditional evaluation. More operators are shown in Table 2. The first six rows explain the numeric comparisons and the last three rows explain operators for multiple comparisons. The latter describe that you can have multiple tests within one if-statement. 

Table 1. Conditional evaluation operators.
Comparison Symbol Example
Equality
==
x == 5
Inequality
!=
x != 5
Less than
<
x < 5
Less than or equal
<=
x <= 5
Greater than
>
x > 5
Greater than or equal
>=
x >= 5
AND
&&
x > 5 && y < 5
OR
||
x == 5 || y == 5
NOT
!
!(x == 5 | y == 5)

We now have made a simple if-statement, let’s take it a step further by introducing the else-if-statement.

Our next step in the coffee-example is to add the time. Let’s say that we cannot drink coffee after 16:00 as we want to be able to sleep at night. In the flowchart below you can see that we added a second path. To add this statement, we will need an extra variable, the time. This time needs to be a number as time is not a recognised value in MATLAB. Let’s imagine it is 15:00, so we set the time variable to 1500.

Figure 5. Flow chart to decide if it is time for coffee (Part 2).
				
					% Variables
cups            = 4;
Tired           = false;
current_time    = 1500; % = 15:00

% If-statement
if Tired == true
    disp("Get coffee");
elseif current_time < 1600
    disp("Okay, 1 more. Otherwise no sleep for you");
else
    disp("No coffee for you");
end
				
			

In this if-statement, the output will be displayed in the Command Window. However, you can imagine that you can put almost anything here. Think about a test which will check if your data is normally distributed, if yes, then calculated the mean. And if the data is not normally distributed, will calculate the median.

EXERCISE 3

During the second part of the tutorial we made a if-else-statement. This exercise will check how well you are understanding the concept of flow control.  As you may have noticed, we included a variable that is not used yet.

  1. See if you can find a way to add an extra if/elseif-statement to the example. Try to really think about what you want to check and what the output should be. Hint: try and draw the flow chart and add it there first. 
  2. Can you think of any other everyday things of which you could make if/elseif-statement.

Concluding remarks #

Plotting the data allows us to graphically distill information from data. If and else statements allow you to provide flexibility to your script. Such flow control allows your code to adapt itself to the data. 

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

Is this article useful?