Modeling and Simulation Lab
Modeling and Simulation Lab
5.2 Introduction
When using MATLAB for biomedical problems, we may be working with large amounts of data that
are saved in an external file. Therefore, it is important to know how to load data from, and save data
to, external files. When writing data items to a text file, we normally need a special character called a
delimiter that is used to separate one data item from the next. We can save data delimited in this way
with the dlmwrite command as illustrated in the following example.
>> f = [1 2 3 4 9 8 7 6 5];
>> dlmwrite('test.txt',f,'\t');
Here, the three arguments of dlmwrite specify the file name (a string), the variable containing the data
to be saved, and the delimiter or symbol that will be used in the file to separate the array values (as a
single character). In this command the file delimiter is a '\t' character, which refers to a tab character.
We could have used another character as a delimiter, e.g. ',' or '-'. The dlmwrite command can be
useful if we need to write data in a particular format to be read in by another software application.
The load and save commands are probably the most used commands for reading and writing data.
The following commands illustrate the use of load and save.
>> d = load('test.txt');
>> e = d / 2;
>> save('alldata.mat');
>> clear
>> load('newdata.mat')
When using the save command the first argument specifies the name of the file to be saved and any
subsequent arguments specify which variable(s) to save inside the file. Omitting the variable name(s)
will cause the entire workspace to be saved. save will create a MATLABspecific binary file containing
the variables and their values that can be loaded in again at any time in the future. These binary files
are called MAT files and it is common to give them the file extension ‘. mat’. The load command can
be used to read either text files created by dlmwrite or binary MAT files created by save. Note that
when using the load command with a text file we should assign the result of the load into a variable
for future use (e.g., see the difference between the first and the last commands above). The clear
command removes all current variables from the workspace.
An alternative, and easier, way of loading MAT files into the workspace is to simply use the MATLAB
environment to drag-and-drop the appropriate file icon from the current folder window to the
workspace browser (or just double-click on it in the current folder window).
Finally, the import data wizard can often be the quickest and easiest way to read data from text files
(i.e. not MAT files). Selecting the Import Data button on the Home tab will bring up a wizard in which
we can choose the file and interactively specify delimiters and the number of header lines in the file.
We will look again in more detail at the subject of MATLAB file input/output functions later.
As well as accessing and manipulating data, MATLAB can also be used to visualize it. The plot command
is used for simple data visualization.
5.3.1 Example
>> y = sin(x);
>> plot(x,y,'-b');
This should produce the output shown in Fig.5.1. The first line in the code uses the colon operator to
create an array called x containing numbers that start with 0, and go up to 2π in steps of 0.1. This array
acts as the x coordinates for the plot. The second line applies the built-in MATLAB sin function to every
element of x. The resulting array acts as the y coordinates for the plot. Finally, the third line of code
displays the graph using the plot command. The first two arguments are the x and y coordinate arrays
(which must be of the same length). The third argument specifies the appearance of the line.
Figure 5.1 Plots of a sine wave between (a) 0 and 2π; (b) 0 and π. Plot (b) also has annotations. Left (a) and Right (b)
Table 5.1 summarizes the different symbols that can be used to control the appearance of the line and
the markers. All these symbols can be included in the third string argument to the plot command. Try
experimenting with some of these to see the effect they have. Next, we will add some text to our plot.
Try typing the following commands to add a title and labels for the x and y axes respectively.
>> title('Plot of sine wave from 0 to 2\pi');
>> ylabel('Sine');
If we only wish to visualize the plot for values of x between 0 and π, the axis command can be used to
specify minimum and maximum values for the x and y axes.
This should produce an output plot zoomed to the x range from 0 to π, and the y range from 0 to 1.
Sometimes we may want to display two or more curves on the same plot. This is possible with the plot
command as the following code illustrates.
>> y2 = cos(x);
>> legend('Sine','Cosine');
We can display multiple curves by just concatenating groups of the three arguments in the list given
to the plot command, i.e. x data, y data, line/marker style, etc. The legend command adds a legend to
identify the different curves. The legend command should have one string argument for each curve
plotted. Finally, note that we can close all figure windows that are currently open by typing
Earlier we saw how to use the MATLAB plot function to produce line plots. We also introduced a
number of MATLAB commands to annotate plots produced in this way (e.g. title, xlabel, ylabel, legend,
etc.). Most of these annotation commands are applicable to other types of plot, as we will see later.
However, plot is only suitable for relatively simple data visualizations, such as visualizing the
relationship between two variables or plotting a 1-D signal. In this lab we will introduce further built-
in MATLAB functions that provide more flexibility when producing data visualizations.
It is often useful to be able to view multiple visualizations at once, for example to enable us to compare
the variations of different variables over time. There are several ways in which we can do this using
MATLAB.
5.4.1 Example
The easiest way to visualize different variables is to carry out multiple plots, either within the same
figure or in separate figures. For example, earlier we saw how to display multiple plots on the same
figure using the plot function:
x = 0:0.1:2*pi;
y = sin(x);
y2 = cos(x);
plot(x,y,'-b', x,y2,'--r');
legend('Sine','Cosine');
The plot function can take arguments in sets of three (i.e. x data, y data, and line/marker style). Each
set will represent a different line plot in the figure.
5.4.2 Example
Alternatively, if we have many plots to display, perhaps within a loop in our program, it may be more
convenient to make separate calls to the plot command to produce our figure. We can do this using
the MATLAB hold command, as the following example illustrates.
x = 0:0.1:2 pi;
y = sin(x);
y2 = cos(x);
plot(x,y,'-b');
hold on;
plot(x,y2,'--r');
legend('Sine', 'Cosine');
The command hold on tells MATLAB to display all subsequent plots on the current figure without
overwriting its existing contents (the default behavior is to clear the current figure before displaying
the new plot). This behavior can be turned off using the command hold off.
5.4.3 Example
Sometimes, displaying too many plots on the same figure can make visualization more difficult.
Alternatively, the plots may represent completely different variables on the x and/or y axes which
cannot easily be plotted together in a single figure. In such cases we can use multiple figures. We can
achieve this in MATLAB using the figure command, e.g.
x = 0:0.1:2 pi;
y = sin(x);
y2 = cos(x);
plot(x,y);
title('Sine curve');
figure;
plot(x,y2);
title('Cosine curve');
Here, the figure command tells MATLAB to create a new figure window (keeping any existing figure
windows intact) and to make it the current figure. Any subsequent plotting commands will be
displayed in the new figure.
5.4.4 Example
Creating multiple figures as in the previous examples can be useful, but we might prefer not to
generate too many figure windows. An alternative way of generating multiple separate plots is to use
subplots within a single figure. The MATLAB subplot command allows us to do this, as this example
illustrates.
x = 0:0.1:2 pi;
y = sin(x);
y2 = cos(x);
subplot(2,1,1);
plot(x,y);
title('Sine curve');
subplot(2,1,2);
plot(x,y2);
title('Cosine curve');
This code produces the output shown in Fig. 5.2. From the code shown above, we can see that subplot
takes three arguments. The first two are the numbers of rows and columns in the rectangular grid of
subplots that will be created (in this case, 2 rows and 1 column). The third argument is the number of
the current subplot within this grid, i.e. where subsequent plots will be displayed. MATLAB numbers
its subplots using the ‘row major’ convention: the first subplot is at row 1, column 1, the second
subplot is at row 1, column 2, and so on.
5.4.5 Example
Finally, there is occasionally a requirement to display multiple plots on the same figure with different
scales and/or units on their y-axes. The following example illustrates this. This is a program that
visualizes two exponentially decaying oscillating functions with very different scales. The output of the
program is shown in Fig. 8.2. The built-in MATLAB function yyaxis is used to display a single plot with
two different y-axes: the left and right axes. The command yyaxis left means that all subsequent plots
and annotations will relate to the left-hand y-axis, whereas yyaxis right activates the right-hand y-axis.
Note that the scales of the y-axes are determined automatically by the ranges of the two datasets (y1
and y2). The two datasets share a common x-axis.
% generate data
x = 0:0.01:20;
% produce plots
figure;
yyaxis left;
plot(x,y1);
% annotate plots
Often when working in biomedical applications it is useful to be able to visualize and analyze data
points in 3-D space: in this case the individual data are the points, and each point has three associated
values (its x, y and z coordinates). Alternatively, we might have a range of measurements related to
hospital patients’ health (e.g. blood pressure, cholesterol level, BMI, etc.): in this case the individuals
are the patients and there will be multiple measurement values for each patient. This type of data is
called multivariate data.
5.5.1 Example
The first command we will discuss for visualizing multivariate data is the plot3 function. The following
example (adapted from the MATLAB documentation) illustrates the use of plot3. This program will
display a helix, and its output is shown in Fig. 8.4.
The first three (non-comment) program statements set up the array variables for storing the x, y and
z coordinates of the helix. These three arrays will all have the same number of elements, which
corresponds to the number of 3-D points. Each 3-D point will take its coordinates from the
corresponding elements in the arrays. The plot3 function takes four arguments: the first three are the
arrays of coordinates, and the fourth (optional) argument specifies the line/marker appearance, i.e.
the same as for the plot function. Note that the same annotation commands (title, xlabel, etc.) can be
used with figures produced by plot3, but that now we have an extra axis to annotate using zlabel.
ct = cos(t);
% 3-D plot figure;
plot3(st,ct,t, '.b')
title('Helix');
xlabel('X');
ylabel('Y');
zlabel('Z');
MATLAB also provides two built-in functions for visualizing multivariate data as surfaces: mesh and
surf. An example of such a visualization is shown in Fig. 8.5a, which is the output of the program shown
in Example below. This type of plot is commonly used for visualizing data in which there is a single z
value for each point on an x–y plane.
5.5.2 Example
In this example (adapted from the MATLAB documentation) a mesh and surf visulaization is produced
to illustrate the sinc function (i.e. sin(x)/x).
Z = sin(R)./R; figure;
surf(X,Y,Z);
The built-in MATLAB meshgrid command creates two rectangular arrays of values to define the x–y
grid over which the mesh is plotted. One array indicates the x-coordinate at each grid point and the
corresponding element in the other array indicates the grid point’s y-coordinate. Arrays of this form,
together with a corresponding array of z values, are the arguments required by the mesh command.
The values calculated for the z-coordinate array are the distances from the origin of each grid point,
after applying the sinc function. Note the use of the .^ operator to square the x and y coordinates: this
is necessary to ensure that the ^ operator is applied element-wise to the array (rather than performing
a matrix power operation. The eps constant in MATLAB returns a very small floating point number and
is necessary to avoid a division-by-zero error at the origin of the x–y plane.
The surf command has the same form as mesh, as we can see from the commented-out command in
the code above. The result of using surf is to produce a filled surface rather than a wireframe mesh
(see Fig.5.5)
Figure 5.5 Output of sinc function using mesh and surf commands
5.6 Tasks
5.6.1 The Injury Severity Score (ISS) is a medical score to assess trauma severity. Data on ISS
and hospital stay (in days) have been collected from a few patients who were admitted to
hospital after accidents. The ISS data are [64 35 50 46 59 41 27 39 66], and the length of stay
data are [8 2 5 5 4 3 1 4 6]. Use MATLAB to plot the relationship between ISS and hospital stay.
Then, fit a linear regression line to these data and estimate what length of hospital stay would
be expected for a patient with an ISS of 55.
Code
clc;
clear;
close all;
data=[64,35,50,46,59,41,27,39,66];
stay=[8,2,5,5,4,3,1,4,6];
A=[data(:) ones(length(data),1)];
b=stay(:);
C=A\b;
plot(data,stay,'o',sort(data),polyval(C,sort(data)));
ceil(polyval(C,55))
Output
Figure 5.6
Figure 5.7
5.6.2 The file patient_data.txt contains four pieces of data for multiple patients:
whether they are a smoker or not (‘Y’/‘N’), their age, their resting heart rate and their
systolic blood pressure. Write a program to read in these data and produce separate
arrays of age and heart rate data for smokers and nonsmokers.
Produce plots of age against heart rate for smokers and for non-smokers,
.txt file
Figure 5.8
Code
fid=fopen('patient_data.txt');
data=textscan(fid,'%c %d %d %d');
fclose(fid);
Ages_of_smokers=data{2}(data{1}=='Y');
A1=sort(Ages_of_smokers);
Heartrate_of_smokers=data{3}(data{1}=='Y');
H1=sort(Heartrate_of_smokers);
Systolic_BP_of_smokers=data{4}(data{1}=='Y');
S1=sort(Systolic_BP_of_smokers);
Ages_of_nonsmokers=data{2}(data{1}=='N');
A2=sort(Ages_of_nonsmokers);
Heartrate_of_nonsmokers=data{3}(data{1}=='N');
H2=sort(Heartrate_of_nonsmokers);
Systolic_BP_of_nonsmokers=data{4}(data{1}=='N');
S2=sort(Systolic_BP_of_nonsmokers);
plot(A1,H1,'-b',A2,H2,'-r');
xlabel('Age');
ylabel('Heart rate');
Output
Figure 5.9
• On the same figure using the hold command.
Code
fid=fopen('patient_data.txt');
data=textscan(fid,'%c %d %d %d');
fclose(fid);
Ages_of_smokers=data{2}(data{1}=='Y');
A1=sort(Ages_of_smokers);
Heartrate_of_smokers=data{3}(data{1}=='Y');
H1=sort(Heartrate_of_smokers);
Systolic_BP_of_smokers=data{4}(data{1}=='Y');
S1=sort(Systolic_BP_of_smokers);
Ages_of_nonsmokers=data{2}(data{1}=='N');
A2=sort(Ages_of_nonsmokers);
Heartrate_of_nonsmokers=data{3}(data{1}=='N');
H2=sort(Heartrate_of_nonsmokers);
Systolic_BP_of_nonsmokers=data{4}(data{1}=='N');
S2=sort(Systolic_BP_of_nonsmokers);
plot(A1,H1);
xlabel('Age');
ylabel('Heart rate');
hold on
plot(A2,H2);
Figure 5.10
Code
fid=fopen('patient_data.txt');
data=textscan(fid,'%c %d %d %d');
fclose(fid);
Ages_of_smokers=data{2}(data{1}=='Y');
A1=sort(Ages_of_smokers);
Heartrate_of_smokers=data{3}(data{1}=='Y');
H1=sort(Heartrate_of_smokers);
Systolic_BP_of_smokers=data{4}(data{1}=='Y');
S1=sort(Systolic_BP_of_smokers);
Ages_of_nonsmokers=data{2}(data{1}=='N');
A2=sort(Ages_of_nonsmokers);
Heartrate_of_nonsmokers=data{3}(data{1}=='N');
H2=sort(Heartrate_of_nonsmokers);
Systolic_BP_of_nonsmokers=data{4}(data{1}=='N');
S2=sort(Systolic_BP_of_nonsmokers);
plot(A1,H1,'-b');
xlabel('Age');
ylabel('Heart rate');
figure;
plot(A2,H2,'-r');
xlabel('Age');
ylabel('Heart rate');
Output
Figure 5.11
Figure 5.12
Code
fid=fopen('patient_data.txt');
data=textscan(fid,'%c %d %d %d');
fclose(fid);
Ages_of_smokers=data{2}(data{1}=='Y');
A1=sort(Ages_of_smokers);
Heartrate_of_smokers=data{3}(data{1}=='Y');
H1=sort(Heartrate_of_smokers);
Systolic_BP_of_smokers=data{4}(data{1}=='Y');
S1=sort(Systolic_BP_of_smokers);
Ages_of_nonsmokers=data{2}(data{1}=='N');
A2=sort(Ages_of_nonsmokers);
Heartrate_of_nonsmokers=data{3}(data{1}=='N');
H2=sort(Heartrate_of_nonsmokers);
Systolic_BP_of_nonsmokers=data{4}(data{1}=='N');
S2=sort(Systolic_BP_of_nonsmokers);
subplot(1,2,1);
plot(A1,H1,'-b');
xlabel('Age');
ylabel('Heart rate');
subplot(1,2,2);
plot(A2,H2,'-r');
xlabel('Age');
ylabel('Heart rate');
Output
Figure 5.13
Code
fid=fopen('patient_data.txt');
data=textscan(fid,'%c %d %d %d');
fclose(fid);
Ages_of_smokers=data{2}(data{1}=='Y');
A1=sort(Ages_of_smokers);
Heartrate_of_smokers=data{3}(data{1}=='Y');
H1=sort(Heartrate_of_smokers);
Systolic_BP_of_smokers=data{4}(data{1}=='Y');
S1=sort(Systolic_BP_of_smokers);
Ages_of_nonsmokers=data{2}(data{1}=='N');
A2=sort(Ages_of_nonsmokers);
Heartrate_of_nonsmokers=data{3}(data{1}=='N');
H2=sort(Heartrate_of_nonsmokers);
Systolic_BP_of_nonsmokers=data{4}(data{1}=='N');
S2=sort(Systolic_BP_of_nonsmokers);
subplot(2,1,1);
plot(A1,H1,'-b');
xlabel('Age');
ylabel('Heart rate');
subplot(2,1,2);
plot(A2,H2,'-r');
xlabel('Age');
ylabel('Heart rate');
title('Age vs Heart rate');
Output
Figure 5.14
5.6.3 Using the same patient_data.txt file you used previously, write a MATLAB program
to produce a 3-D plot of the patient data. The three coordinates of the plot should be
the age, heart rate and blood pressure of the patients, and the smokers and non-
smokers should be displayed using different symbols on the same plot. Annotate your
figure appropriately by, for example, inserting suitable labels on the axes.
Code
fid=fopen('patient_data.txt');
data=textscan(fid,'%c %d %d %d');
Ages_of_smokers=data{2}(data{1}=='Y');
A1=sort(Ages_of_smokers);
Heartrate_of_smokers=data{3}(data{1}=='Y');
H1=sort(Heartrate_of_smokers);
Systolic_BP_of_smokers=data{4}(data{1}=='Y');
S1=sort(Systolic_BP_of_smokers);
Ages_of_nonsmokers=data{2}(data{1}=='N');
A2=sort(Ages_of_nonsmokers);
Heartrate_of_nonsmokers=data{3}(data{1}=='N');
H2=sort(Heartrate_of_nonsmokers);
Systolic_BP_of_nonsmokers=data{4}(data{1}=='N');
S2=sort(Systolic_BP_of_nonsmokers);
plot3(A1,H1,S1,'-+',A2,H2,S2,'-^');
xlabel('Age');
ylabel('Heart rate');
legend('Smokers age vs Heart rate vs Systolic Blood Pressure','Non smokers age vs Heart rate vs
Systolic Blood Pressure');
Output
Figure 5.15