Matlab Tutorial_Week 1and20

advertisement
INTRODUCTION TO MATLAB
Week 1 Tutorial
INTRODUCTION

Matlab (short for MATrix LABoratory) is a language for technical
computing, developed by Mathworks, Inc.

It provides a single platform for computation, visualisation,
programming and software development.

Matlab is a perfect choice for use with medical data.

Matlab is very powerful and essentially involves operations using
matrices and vectors (arrays).



Over the duration of this module you will be learning, through practical
exercises, how Matlab can be used to visualize and manipulate medical
data.
You will also (Wk 9, 10) learn how to perform classification and data
clustering using matlab.
The Matlab software environment has a core module (called Matlab)
and associated with that are a set of ‘Toolboxes’ that perform
specialized computations.
TUTORIAL OVERVIEW


In this tutorial, we will introduce some of the
basic components of Matlab in preparation for
the first Matlab tutorial in week 3.
The aim is to provide everyone with a basic
understanding.
Therefore we will work through the concepts slowly.
 Feel free to ask questions throughout.

LETS BEGIN

Getting Started.

Matlab should be available in 16C29, where your practical labs will be held
– look for the Matlab icon on the desktop.

Note: In all of the discussion in the following sections, stuff that you type
into Matlab will be presented in boldface.

Double click on the Matlab icon to start the program.

To get started, type one of these commands: helpwin, helpdesk, or demo.

The ">>" is a prompt, requiring you to type in commands. One of the first
commands you should type in is to find out what your working directory is. The
working directory is where you will save the results of your calculations. So, type
in >> pwd (stands for "print working directory".

Matlab always stores the result of its last calculation in a variable called ans (short
for answer).

You can change the working directory using the cd (short for change directory)
command. Do >> cd C:\temp
VECTORS AND MATRICES (1)

Variables in Matlab are just like variables in any other programming
language.





only difference is that you do not have to define them by indicating the
type etc.
Also, variable names (case sensitive) can be used to refer to a single
number, a set of numbers (vector) or an array of numbers (matrix).
Vectors are nothing but matrices having a single row (a row vector), or a
single column (a column vector).
To create a row vector in Matlab, do:

>> r = [1 2 3 4]

r=1
2
3
4
A column vector can be created by


>> c = [1; 2; 3; 4]
c= 1
2
3
4
VECTORS AND MATRICES (2)

On the other hand, you can use the ' operator (transpose) to
flip the row vector created.



2
3
4
Vectors can also be created by incrementing a starting value with a
constant quantity. For example,



>> c = r'
c= 1
>> r = [0:2:10]
r = 0 2 4 6 8 10 creates a row vector, with the first element = 0;
each element incremented by 2; until the final value of 10.
You can index specific parts of a vector. For example, to get the third
element in the vector r, you can do


>> r(3)
ans = 4
VECTORS AND MATRICES (3)

Matrices are 2 dimensional quantities and are created
similar to vectors. We can do
 >>
a
a = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
=
7
 which
8
1
9
2
3
10
4 5
11 12
is a 4x3 matrix (4 rows and 3 columns).
6
VECTORS AND MATRICES (4)

We can also use the incrementation principle to do



>> b = [0:2:10; 1:2:11]
b=
1 3
5
0
7
2
9
4
11
6
8
10
which is a 2x6 matrix. Again, individual elements of the
matrix, for instance the element in the 2nd row, 5th column
can be accessed using the notation:

>> b(2, 5)

ans = 9
VECTOR AND MATRIX OPERATIONS (1)

The basic arithmetic operations +, -, *, / can be used for vectors and matrices.

These generate corresponding output vectors or matrices.

For example, to add two vectors:




>> a = [1 2 3 4];
>> b = [5 6 7 8];
>> c = a+b


c = 6 8 19 12
The semicolons (;) in the first two commands direct Matlab not to echo the values of
the variables a and b on to the screen immediately after you type them.
Obviously, only vectors that have the same number of elements can be added or
subtracted. Similarly, two matrices with identical number of rows and columns
can be subtracted as follows:



>> m = [1:2:9; 10:2:19];
>> b = [2:2:10; 11:2:20]
>> c = m-b

c = -1
-1
-1
-1
-1
-1
-1
-1
-1
-1
VECTOR AND MATRIX OPERATIONS (2)






Matrix multiplication using the * symbol is possible only if
the number of columns in the first matrix equals the
number of rows in the second:
>> a=[1 2 3; 4 5 6]
a= 1 2 3
>> b = a’
b= 1 4
>> c=a*b
c = 14 32
2
4
5
ROW

32
77
5
3
6
6
COLUMN
DELETING ROW / COLUMN ITEMS

To delete a row or column of a matrix, use the empty vector operator,
[ ].

>> A(3,:) = [ ]
>>A =
123
456

Third row of matrix A is now deleted.

To restore the third row, we use a technique for creating a matrix




>> A = [A(1,:) ; A(2,:); [7 8 0]]
>>A = 1 2 3
456
789
Matrix A is now restored to its original form.
LOOPS








The for loop is a simple command for setting up a loop.
>> a = [];
>> for i = 1:10; >> a(i) = i*i; >> end
>> a
a = 1 4 9 16 25 36 49 64 81 100
All statements between the for and the end statements will
be executed as per the command specifications. Example of
a for loop where the increment is not 1 would be
>> for i = 1:3:20; ..... etc.
Type in >> help for for more details.
INTRODUCTION TO MATLAB
Week 2 Tutorial
WHY CHOOSE MATLAB? (1)


Matlab is currently widely used as a platform for
developing tools for Decision Support
Why it is useful for prototyping AI projects:
large toolbox of numeric/image library functions
 very useful for displaying, visualizing data
 high-level: focus on algorithm structure, not on low
level details
 allows quick prototype development of algorithms

WHY CHOOSE MATLAB? (1)

Matlab is an interpreter -> not as fast as compiled code

Typically quite fast for an interpreted language

Often used early in development -> can then convert to C
(e.g.,) for speed

Can be linked to C/C++, JAVA, SQL, etc

Commercial product, but widely used in industry and
academia

Many algorithms and toolboxes freely available

netlab
SAVING YOUR WORKSPACE


It is possible to save your workspace.
This is the area in which all of you created variables
are.

Be aware, this can become very large!

>> save {name is optional}

Typing ‘save’ on its own will create a file called
‘matlab.mat’ in the working directory.

Typing ‘load {name is optional} will load the workspace.
FILE INPUT / OUTPUT

The save and load commands are used for saving data to
disk or loading data from disk, respectively.

To save values in a matrix or vector, called, for instance, y, do:





The -ascii option ensures that the data is saved in ASCII form,
so that it can be read by other programs - Word, Excel
Notepad, Wordpad, etc.
Examine the file y.txt using one of these programs. The file is
generated in the working directory.
An ASCII data file sample.txt can be loaded using


>> y = [1 2 3 4; 5 6 7 8];
>> save sample.txt y -ascii
>> load sample.txt
Do >>help save and >>help load for more on load/save
options.
PLOTTING

The plot command is used for generating 2-D
(functions of one variable) plots.

Do >> help plot for complete details.

>> x = [0:0.1:10]; %(here .1 is the increment)

>> y = sin(x); %(notice how the sin function operates on each element of
the entire row vector x, to generate a nother row vector y)

>> plot (x, y)

>> clf

To generate another plot window, do >> figure
(clear graph)
2-D PLOTTING












x=0:.1:2*pi;
y=sin(x);
plot(x,y)
grid on %grid on
hold on %add extra to graph
plot(x, exp(-x), 'r:*')
axis([0 2*pi 0 1])
title('2-D Plot') %title
xlabel('Time') %labels
ylabel('Sin(t) ')
text(pi/3, sin(pi/3), '<--sin(\pi/3) ') % add some text
Legend('Sine Wave', 'Decaying Exponential') % legend
LINE CHARACTERISTICS
PLOTTING
x = rand(1,100);
 y = rand(1,100);
 plot(x,y,'*')

% To put a label on the axes we would use:
 xlabel ('X-axis label')
 ylabel ('Y-axis label')
 % To put a title on the plot, we would use:
 title ('Title of my plot')

FIGURE WINDOW


The figure window contains useful actions in its menu
and toolbars:






Zooming in and out
Rotating 3-D axes (and other camera actions)
Copying & pasting
Plot Edit Mode
Property Editor
Saving & Exporting

Figures can be saved in a binary .fig file format

Figure can be exported to many standard graphics file formats
etc.,


GIF, PNG, JPEG, TIFF, BMP, PCX, EPS.
Printing
EXECUTABLE FILES (M-FILES IN MATLAB)

Executable files in Matlab are generated by storing a list of Matlab commands
in a file given the extension .m



These files are called M-files.
To create an M-file, use the New...M-file Option under the File Menu in the Command
Window.
Type in the following commands in the M-File Editor Window:
x = [2:3:38];
y = [1 3 11 45 67 105 102 65 56 32 11 3 1];
plot(x,y)
xlabel('x')
ylabel('y')

Save the file using the Save Option under the File Menu in the M-File Editor
Window. Call it, say, sample.m.

Now, to run this program in Matlab, move over to the Matlab Command
Window and just type in >> sample
PLOTTING MEDICAL DATA (1)

EMG Data – electrical signals representing muscle movement
on the forearm resulting from gross finger movement.
>> plot(finger1)
>> axis([0,500,60,200])
>> figure
>> plot(finger2)
>> axis([0,500,60,200])
>> figure
>> plot(finger3)
>> axis([0,500,60,200])
>> figure
>> plot(finger4)
>> axis([0,500,60,200])
PLOTTING MEDICAL DATA (2)
>> figure
 >> hold on
 >> plot(Average1,'r','LineWidth',1.5)
 >> plot(Average2,'g','LineWidth',1.5)
 >> plot(Average3,'b','LineWidth',1.5)
 >> plot(Average4,'k','LineWidth',1.5)
 >> hold off


SUBPLOTS









Subplot (m x n, position)
subplot(2,2,1)
plot (Average1)
subplot(2,2,2)
plot (Average2)
subplot(2,2,3)
plot (Average3)
subplot(2,2,4)
plot (Average4)
subplot(2,2,1)
plot(Average1,'r','LineWidth',1.5)
subplot(2,2,2)
plot(Average2,'g','LineWidth',1.5)
subplot(2,2,3)
plot(Average3,'b','LineWidth',1.5)
subplot(2,2,4)
plot(Average4,'k','LineWidth',1.5)
PLOTTING MEDICAL DATA (3)




ECG – The contraction of the heart muscle is caused by an
electrical charge, originating from within the heart itself.
This charges travels to the body surface
Electrodes can be placed on the body and used to read the
electrical activity.
Plot (x1)
CONTOUR PLOTS








%contour plot
contour(example)
%coloured contour plot
contourf(example)
%more contours
contourf(example,100)
%Coloured contour plot with edge line removed
contourf(example,'EdgeColor','none')
SURFACE PLOTS








%simple surface plot
surf(example)
%surface plot with colourbar
surf(example,'EdgeColor','none')
colorbar
%interpolated surface plot with contour plot
surfc(example,'EdgeColor','none')
shading interp
ADVANTAGED GRAPHING

example = mapper(x,y,tempArray1(1,5:121))
MORE SUBPLOTS
subplot(1,2,1)
 surfc(example,'EdgeColor','none')
 set(gca,'YDir','reverse');
 shading interp
 axis square

subplot(1,2,2)
 contourf(example,'EdgeColor','none')
 set(gca,'YDir','reverse');
 axis square

PLOTTING A SEQUENCE
%Plot multiple bspms in sequence
for i = 1:10
hold on
mapper(x,y,tempArray1(i,5:121))
pause
end
hold off
SUMMARY

Matlab is the perfect choice for working with large amounts
of medical data.

When faced with the task of having to classify medical data
into a number of different categories.

Healthly and Unhealthy

The first step is usually to graph the data.

Graphing allows us to quickly assess vast amounts of data.

Later in the module you will be given simple classification
tasks.

Consider graphing the ‘problem’ first to gain insight into the
structure of the data and relationship between variables.
Download