MATLAB tutorial Student version
11 Pages
English

MATLAB tutorial Student version

-

Downloading requires you to have access to the YouScribe library
Learn all about the services we offer

Description

A K V A M O D Integrating education in the Ø r e s u n d region Modelling Aquatic systems – Connecting research Basic MATLAB tutorial for AKVAMOD partners Anders Brodin Theoretical Ecology, Lund University INTRODUCTION This is a brief introduction to MATLAB for those of you that have not previously used this program but it may also be useful for those of you that need to refresh things that you have forgotten. Its main purpose is to make you comfortable enough so that you can do the MATLAB exercises that are available for download here at AKVAMOD. The compendium ends with a more detailed section about programming. This compendium is interactive, meaning that you should be sitting at a computer while you read this and work through the exercises. The exercises in this compendium are checked on MATLAB 7.0 for Windows, 2004, but it will probably work on other platforms as well. WHAT IS MATLAB? MATLAB is short for MatrixLaboratory. Those of you who are familiar with matrices and vectors will then realize that MATLAB originally was designed for matrix operations such as linear algebra calculations. Those of you that are not familiar with such operations should not worry, however. Nowadays, MATLAB has become a full-grown environment for advanced mathematical functions and methods for graphic visualization of data. At the same time as many functions for numerical calculations and graphics have been included, MATLAB also ...

Subjects

Informations

Published by
Reads 25
Language English
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
Basic MATLAB tutorial
for
AKVAMOD
partners
Anders Brodin
Theoretical Ecology, Lund University
INTRODUCTION
This is a brief introduction to MATLAB for those of you that have not previously used
this program but it may also be useful for those of you that need to refresh things
that you have forgotten. Its main purpose is to make you comfortable enough so that
you can do the MATLAB exercises that are available for download here at AKVAMOD.
The compendium ends with a more detailed section about programming. This
compendium is interactive, meaning that you should be sitting at a computer while
you read this and work through the exercises. The exercises in this compendium are
checked on MATLAB 7.0 for Windows, 2004, but it will probably work on other
platforms as well.
WHAT IS MATLAB?
MATLAB is short for MatrixLaboratory. Those of you who are familiar with matrices
and vectors will then realize that MATLAB originally was designed for matrix
operations such as linear algebra calculations. Those of you that are not familiar with
such operations should not worry, however. Nowadays, MATLAB has become a full-
grown environment for advanced mathematical functions and methods for graphic
visualization of data. At the same time as many functions for numerical calculations
and graphics have been included, MATLAB also has its own programming language
that is developing into a modern, high-level programming software.
MATLAB consists of several main parts of which you need to know:
1. The development environment which consists of things that you need to use
MATLAB. Some examples are the command window, the command history, the
workspace, the current directory, etc.
2. MATLAB’s library of mathematical functions, Mathematical Function Library. There
are functions ranging from simple mean calculations to complex mathematical
computations.
3. The MATLAB programming language.
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
Before we go on to the actual software it might be useful with to remind you of the
concept of a matrix. It can be seen as a rectangular table holding numbers. A 1 x 1
matrix is called a scalar and a matrix with only one column or one row is called a
vector.
EXERCISE
On your screen MATLAB will appear as a desktop, probably consisting of five docked
parts:
Launch pad, Work space browser, Command window, Command history and
the Current directory. The functions of the most important of these are:
Command window
– this is the main window where you can write commands at a
prompt. You can type commands, for example variables or files. Originally MATLAB
was not as ”Window-adapted” as in the current environment, and all commands had
to be written at the prompt. This means that most commands that are available in
the windows menus also are available as prompt commands.
Work space browser
– can be used during debugging to check values of active
variables and matrices (in fact variables in MATLAB are matrices by default).
Current directory
– shows the files the current library, for example ”work” were
MATLAB save your files unless you specify another library.
There are two other important parts of MATLAB that did not open by default. These
are the Editor/debugger and the help browser. Their functions are evident:
Editor/debugger
- is the word processor where you type in your programming
code. “Debugger” means that there are falities that will help you to track
programming errors (bugs) in it.
Help
browser - MATLAB has an incredibly large help browser, in fact it is almost as
large in megabytes as the rest of the software!
Open the editor, name a file ”DummyProgram” or “MyProgram”and save it.
Rearrange the desktop so that it only contains the windows that you will use most
frequently. These are the Command window, the Help browser and a perhaps the
editor. You cannot do anything with the program you created because it does not
contain anything, just an exercise.
Using the command window
Exercise 2
: At the prompt (>>), type 10 + 2 and then execute this. The following
should appear at your screen:
ans =
12
Apparently you can use the command window as a pocket calculator if you want. The
format of the answer depends on that MATLAB performed the calculation for you, but
since you never created any variable for the answer it used the default one, ans. It
may be neater to create your own variable. Type x = 10 + 2 at the prompt and
execute it. This should produce
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
x =
12
Frequently you may wish to assign values to variables in the computer’s memory but
not displaying them on the screen. In the previous operation you created a variable
called x. To redo this operation (but with a small change), first use the up arrow but do
not press “execute”. The last command you typed should now appear at the prompt (x
= 10 + 2). This is a handy way of repeating previous commands. Before you execute
this, put a semicolon immediately after 2: x = 10 + 2; then execute this.
What happened? Nothing should happen at the screen since the semicolon tells MATLAB
to store the value of x in the memory, but not display this operation. To really check
that the value of x is 12 you can click the “Workspace” tag (it is probably located below
your “Current Directory”). Here you should see that the variables x and ans are active.
If you double-click x its value should be displayed. Since MATLAB consider scalars to be
matrices it will somewhat awkwardly be displayed as a table holding only one value, 12.
Matrix exercises I
Exercise 3
: Create the quadratic matrix A:
8
1
6
3
5
7
4
9
2
by typing
A = [8 1 6; 3 5 7; 4 9 2]
in the command window. Those of who have done some linear algebra will remember
than matrix variables frequently are named by capital letters, here we call it A.
Individual numbers are separated by commas or empty space, end of row is
semicolon. Finally the whole matrix is surrounded by square brackets. Check that the
matrix A also is active in the workspace window.
Exercise
4:
Type the command sum(A). What is the result?
A matrix can be summed either by columns or rows. The default in MATLAB is by
columns so the results should be a row vector holding the sums of the columns.
Since no variable was defined MATLAB will use the default ans =
Evidently the sums were equal for all columns, now let’s sum the rows instead. The
simplest way to do this is to transpose the matrix. This is done by citation mark, for
example B = A’ will create a new matrix called B that is the transpose of A. What was
the sum of the rows (sum(B))?
What type of matrix is this? Try the command magic(x) with x replaced by some
integer number. What is a magic square?
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
Exercise 5
: create a new matrix, A, looking like this:
1
3
5
9
8
4
2
2
2
7
7
1
Use the sum command to produce a column vector and calculate its sum.
Remember that MATLAB by default creates row vectors since it counts by columns. If
you had problems, do this either by creating a new transposed vector, for example B
and write sum(B)’ which should give you the answer 18
16. Alternatively you could
directly write sum(A’).
Exercise 6
: What would sum(A’)’ produce? Why?
There are two diagonals in a matrix. The main one goes from the upper left corner to
the lower right corner.
Exercise 7
: Create a new matrix that is a magic square 6 x 6. Check the main
diagonal with the command diag(C).
What will the command diag(C’) produce and why?
To get the opposite diagonal you must use the flip left right command fliplr.
Exercise 8:
Calculate the sum of the opposite diagonal for matrix C. You could either
do this stepwise and create new matrices or make a direct command.
Frequently you will need to access elements within a matrix. This is done parenthesis
notation A(i,j) where i is row and j column.
Exercise 9:
Sum a diagonal from a magic square accessing the individual elements by
parenthesis notation such as A(i,j).
Parenthesis notation gives you access to individual elements by addressing row and
column. It is perfectly valid to treat a two dimensional matrix as a one-dimensional
column vector. In this case you can address your magic square above as A(x) where
x is any number between 1 and i * j.
Exercise 10:
Redo exercise 9 addressing the square as a vector A(x). This is of
course the standard way to address vectors.
Exercise 11:
Make a 4 x 4 magic square called E. What is E(18)?
Colon is an important feature in MATLAB. The expression a = 1:50 creates a row
vector with from 1 to 10. To increase in steps by 2, instead type a = 1:2:50
Exercise 12:
Create a vector e starting from 100, ending at 50 that decreases by 5 in
each step.
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
Parenthesis combined with colon gives access to parts of matrices. For example
A(1:k,j) produces the elements from 1 to k in column j”.
Exercise 13:
Use parenthesis + colon, A(x:k,j) to calculate the sum of column 3 in a
4 x 4 magic square.
Exercise 14:
Colon by itself means all rows or columns in a vector, i.e. it will give you
all elements in a long row. Sum all elements in the last row in a 5 x 5 magic square
with this notation using the command ”end”. A(end,j) means the last row, A(i,end)
means the last column.
Variables and operators
MATLAB is a weakly typed language, meaning that you do not need to declare
variables or allocate memory when you write code. To name variables you can use
letters, numbers and underscore. Capitals and lower case are separate.
The most common operators are:
Arithmetical:
+
Addition
-
Subtraction
*
Multiplication
/
Division
^
Raised to the power of
Logical (boolean):
&& And
||
Or
~
Not
Relational:
<
Less than
>
Greater than
< =
Less than or equal to
> =
Greater than or equal to
= =
Equal to
~ =
Not equal to
Assignment
=
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
Thus x = 3 means assign the value 3 to the variable x while x = = 3 means x is
equal to 3.
( )
If your are not sure about the order of precedence between these you can always
fix it with parenthesis
MATLAB functions
MATLAB has a large number of prewritten functions that can help you with
calculations and perform tasks for you. You have already used several functions, for
example sum(), diag(), fliplr() and magic(). A function is consists of a chunk of code
that can receive one or several arguments from you and then send something back.
The functions I just mentioned are prewritten and ready to use, but after going
through this compendium you should be able to write your own functions. The
parenthesis can be seen as a functions “inbox”, it contains the arguments that you
want to send to the function. The answer (or return) from the function can be
assigned to a variable by a statement such as:
Y = diag(X)
provided of course that you have a matrix called X that you can send to the function
diag().
Exercise 15:
Create a vector consisting of five integer values inside the parenthesis
so that you send it to the function sum().
Matrix exercises II
Since MATLAB is designed to work with matrices there are several special functions
to create these. For example
zeros – fills a matrix with zeros
ones – fills a matrix with ones
rand – fills a matrix with uniformly distributed random numbers
Exercise 16:
Create a 3 x 3 matrix filled by zeros, a 2x 5 matrix filled by ones and a
4 x 4 matrix filled by random numbers so that they do not appear in the command
window. Print them all afterwards.
To erase a row or a column in a matrix set it equal to empty square brackets =
[ ].
For example E(:,3) = [] erases all elements in row 3 in Matrix E.
Exercise 17:
Create a 10 x 10 magic square B and erase row 5. Check the matrix.
Try the command B(2,2) = []. What happens?
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
Plotting
MATLAB basically plots vectors, for example y versus x. The basic command is plot.
Exercise 18:
Create a vector x filled with elements from 0 to 20 in steps by 0.1.
Create another vector y that is the sine of x. Plot y against x.
Exercise 19
: Label the axes in the plot with the commands:
xlabel(’Time’)
ylabel(’Sine of x’)
title(’My first plot’)
To ensure that a plot is not lost for example when you are doing complex figures with
multiple plots, a plot can be locked with ’hold’ or ’hold on’. To release it use ‘hold’
again or ‘hold off’.
Besides changes in the command window you can also edit plots interactively by
clicking the plot.
MATLAB programming
What is programming?
- Writing instructions that computers understand
Examples of programming languages:
Basic, Cobol, Fortran, Pascal, Assembler language, C, C++, Java, PERL. These
languages are developing at the same time as new ones are born. Here are some
examples of this:
Basic
Visual Basic
C
C++
Visual C, C++ Builder
C
Java
Pascal
TurboPascal
The most basic languages are close to the machine language (which consists of raw
numbers organized in registers), for example assembly language. Such a language is
suitable for writing basic instructions to a pc, but hard to program modern
applications in since it has no prewritten routines and functions. On the other hand it
requires a minimum of computer time and memory. A high level language (such as
MATLAB) contains lots of prewritten functions and useful help facilities. In fact
MATLAB has two levels before your instructions reaches the processor in your
computer since MATLAB itself is written i C. C in turn is on higher level than assembly
language since it has more prewritten functions and conveniences. A more modern
and programmer oriented version of C is C++ that contains more overhead. If you
plan to become a programmer you should probably learn C or C++ instead, but if
you want to program mathematical applications (for example in population ecology)
MATLAB is the right thing for you.
MATLAB code is saved in so called m-files. These can be full functions or simpler
scripts (if you do not remember what a function is, check the explanation above).
Essentially a script is just some rows of code whereas a function can receive and
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
return arguments. The name at the top of the function (or script) should be the same
as the name of the file.
Ctrl C
MATLAB will by default store your files in a directory called ”work”, but you can also
create your own directory if you change the settings, for example “MyCode”. Most
programming languages originate in some way from FORTRAN meaning that they
have similar (but slightly different) commands and syntax. In MATLAB they are very
similar to C, the common ones being:
if, if - else, switch, for, while och break
We will start with the conditional statement “if” in a script. To create the script,
choose “New” and “m-file” in the File menu. Then cut and paste the code below.
The format of an if-statement is:
if “Some conditional statement”
execute som code
end
When the conditional statement is true the code will execute, otherwise it will be
skipped. An if-statement can be extended by and “else”, which will create a dual
choice (either perform a or b:
if “Some conditional statement”
execute a
else
execute b
end
The script is the text between the lines:
____________________________________________________________________
%Exercise written by XXXX
a comment (insert your own name)
a = input('What number is a?
')
%create the variables a and b and
b = input('What number is b?
')
%prompt the user to insert values
n = a + b;
%create a new variable n and assign a
%
+
b
t
o
i
t
c = input('What is the sum of a + b? ')
%create c as input variable
if c == (a + b)
%conditional if statement
' correct! '
else
%if - else command
' wrong'
end
%end of“if statement”
____________________________________________________________________
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
Scripts are the simplest m-files Save the script as a file called “IfLoop”, MATLAB will
automatically insert the extension .m. At the first line there is a percentage sign. This
is used to insert comments, that is, your own text and memos. A program such as
this may not require many comments, but if you write many programs you will soon
forget your old code, maybe not even remember how it was constructed when you go
through it later. Good programmers use many comments. The rest of the code is
explained behind comments.
Now let’s improve the code somewhat.
Exercise 20
. First get rid of some unnecessary printouts in the command window of
type “ans” by using semicolon.
We will now refine the code by requesting that the user can count by using “while”.
We will also change the script to a function:
____________________________________________________________________
function s = IfWhileLoop()
%Exercise written by XXXXXX
%The code will repeat until the answer is correct
a = input('What number is a?
');
b = input('What number is b?
');
n = a + b;
c = input('What is the sum of a + b? ');
if c == (a + b)
s = ' Correct! ';
else
s = ' Wrong'
while
c ~= a + b
%”while” repeats code until condition is true
c = input('What is the sum of a + b? ');
end
%end of while loop
s = ' Correct! ';
end
____________________________________________________________________
As previously explained a function can do more things than a script. Remember that
functions must have the same name as the file they are saved as. The first row tells
MATLAB that you have written a function called “IfWhileLoop”. The statement
“s = Functionname” is a return argument that passes something like a value to
something else, for example another function. It means that the output from the
function (for example the result of some calculation) will be assigned to a variable
called s. Previously I said that the parenthesis after the function name (empty here)
can be seen as the inbox receiving incoming mail to the function. In that case
“variable = Functionname” is the outbox. We did not strictly seen need a function
here, a script could also send output to the command window. In more realistic
applications, however, you will frequently need to pass variable values or memory
addresses between functions within your application.
Exercise 21
:
a) Use “if-statements” to improve the code so it only allows a maximum of five errors
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
b) Use the command “break” instead of if-statements to do this. Break will jump out
of the chunk of code where you are to the next level. For example, if you insert it
between “if” and “end” MATLAB will skip everything between break and end and
continue after end.
“if - else - end” is perfect to choose between two alternatives. To choose between
more than two alternatives you can insert multiple if-statements:
if Condition
perform this code
else
if Another condition
Perform some other code
else
Perform third kind of code
End
End
This is still readable, but imagine what a choice between eight different alternatives
would look like! Instead we can use a multiple choice statement at the same level,
switch. The awkward first line is a call to a MATLAB function called rand, it “seeds”
the random number generator so that we will not get the same sequence of random
numbers every time we open MATLAB (computers cheat when they produce random
numbers, they produce the same sequence every time. This is why they freuqntly are
called pseudo random numbers)).
____________________________________________________________________
function s = SwitchCode
%Exercise written XXXXX by YYYYYY
rand('state',sum(100*clock))
a = rand(1);
a = round(a * 4);
switch a
case 0
s = 'It was 0';
case 1
s = 'It was 1';
case 2
s = 'It was 2';
case 3
s = 'It was 3';
case 4
s = 'It was 4';
otherwise
error('Something is wrong')
end
____________________________________________________________________
Is a function necessary here or will a simpler script do? Well, if ‘s’ is not sent
anywhere a script will do. Finally, ”for” loops may be the most important ones, they
will execute code a specific number of times. As you can notice below I have written
functions rather than scripts even though it is not necessary.
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk
A K V A M O D
I n t e g r a t i n g e d u c a t i o n i n t h e Ø r e s u n d r e g i o n
M o d e l l i n g A q u a t i c s y s t e m s – C o n n e c t i n g r e s e a r c h
___________________________________________________________________
function s = ForLoop
%Exercise written 2/9 200X by YYYYYY
Z = zeros(1,10);
%creates a vector 10 x 1 filled with 0
rand('state',sum(100*clock));
%random numbers decided by clock
for a = 1 : 10
%loops from 1 to 10
b = rand(1);
%gives a random number between 0 and 1
Z(1,a) = b;
%insert the random number in the vector
end
%end of for loop
Z
%output of the vector
___________________________________________________________________
To access a two-dimensional matrix, use nested for loops:
___________________________________________________________________
function s = ForLoops2
%Exercise written XXXX by YYYY
Z = zeros(10);
%creates a 10 x 10 matrix
rand('state',sum(100*clock))
%seed the random number generator once
for a = 1 : 10
%the outer loop (rows)
for b = 1 : 10
%the inner loop (columns)
c = rand(1);
%Random numbers
Z(a,b) = c;
%enter into matrix
end
%end inner loop
end
%end outer loop
Z
%output of Z
___________________________________________________________________
Although superficial, this will hopefully have made you comfortable enough so that
you can enjoy doing some execises in MATLAB.
This material belongs to AKVAMOD
Any copying or use requires permission.
www.Akvamod.dk