Introduction to MATLAB

Belfield
Campus
Map
<D
onn
ybr
ook
Introduction to MATLAB
N11
Entrance
8
25
19
Greenfield
Entrance
50
COMP 50020
15
37
31
34
22
16
14
49
36
21
10
41
29
20
Derek Greene
52
40
38
23
27
17
28
39
32
46
47
63
24
UCD School of Computer Science
and Informatics
62
5
3
1
2
Richview
Entrance
6
4
7
51
35
26
18
61
33
9
42 44
43
30
45
48
2
MATLAB
• MATLAB: An interactive system for doing numerical
computations.
• Simplifies many tasks associated with solving problems
numerically, good for prototyping and rapid development.
• It has been widely used in research in a variety of
different domains.
Integrated
Development
Environment
Console
Interface
3
Octave
• GNU Octave: A high-level language, primarily intended for
numerical computations.
• Designed to be a free open source language that is largely
compatible with the commercial Matlab application.
• Its syntax is very similar to MATLAB, and many scripts will
run on both Octave and MATLAB.
• Octave runs under most Unix and Unix-like operating
systems, as well as Windows.
• Lacks implementations for
advanced toolboxes and has
no graphical IDE.
• Octave v3 does provides an
enhanced console interface.
4
Variables in MATLAB
• Variables are assigned numerical
values by typing the expression:
>> x = 4 + 5
x =
9
• The answer will not be displayed
when a semicolon is put at the end.
• Variable names consist of
any combination of letters
and digits, starting with a
letter.
>>
Valid:
x2, X3, sum2total, u2c45
Invalid:
2total, Total-Value, %x, @sign
• To view the value of a previously
defined variable, type the name of
the variable by itself:
• NB: MATLAB is case-sensitive!
>> x = 4 + 5;
>> x
x =
9
>> x = 4;
>> X
??? Undefined function or variable 'X'.
5
MATLAB Basics
Numeric Types
Type
Examples
• Matlab recognises several
Integer
3434, -23
Real
0.03,1.34,-20.43
Complex
4.4+3.2i
Infinity
Inf
Not a Number
NaN, 0/0
different types of numbers:
Fundamental Operators
• Arithmetic operators in
order of precedence:
Operator Action
• Logical operators in order
of precedence:
Operator Action
^
Raise to the power
~
Not
/
Division
&
Logical And
*
Multiplication
|
Logical Or
-
Subtraction
+
Addition
• These can be
combined to form
boolean expressions:
>> 1 & 0
ans =
0
6
Built-In Functions
Elementary Functions
>> sqrt(25)
• A variety of common mathematical
ans =
functions are available in MATLAB.
Function
Action
sqrt(x)
Square root of x
exp(x)
Exponential of x
log(x)
Natural logarithm of x
log10(x)
Base 10 logarithm of x
abs(x)
5
>> exp(x)
ans =
8.1031e+03
>> log(4)
ans =
1.3863
Absolute value of x
Trigonometric Functions
>> cos(pi/12)
• Standard trigonometric functions
ans =
are also available, and take
parameters in radians.
cos(x), sin(x), tan(x)
0.9659
>> sin(pi/4)
ans =
0.7071
NB: For documentation on a function:
>> help log
help <function name>
LOG
Natural logarithm....
7
Vectors and Matrices
Creating Vectors
• To enter a vector, separate entries by
space(s) and use square brackets to
denote the start and end of the vector.
• To enter a variable with multiple rows,
the rows are separated by semicolons
or by carriage returns.
>> x = [ 3 5 6 11 ]
x =
3
5
6
>> y = [ 2; 4; 8 ]
y =
2
Column
vector
4
8
Creating Matrices
• 2-dimensional matrices can be entered in the same way:


1.6 1.8
 0.4 0.3 
1.2 3.5
>> A = [ 1.6 1.8; 0.4 0.3; 1.2 3.5 ]
A =
1.6000
1.8000
0.4000
0.3000
1.2000
3.5000
11
8
Vectors and Matrices
Other Vector/Matrix Creation Methods
Create a vector from
a predefined range:
>> v = (2:5)
v =
2
Reshaping a vector
into a 2x2 matrix
3
4
5
>> A = reshape(v,2,2)
A =
2
4
3
5
Create an empty
Create a random
matrix with zeros() matrix rand()
Create a diagonal
matrix with diag()
>> B = zeros(2,3)
>> C = rand(2,3)
>> x = [1 2 3];
B =
C =
>> D = diag(x)
0
0
0
0.8147
0.1270
0.6324
0
0
0
0.9058
0.9134
0.0975
D =
1
0
0
0
2
0
0
0
3
9
Vectors and Matrices
Accessing Vector/Matrix Elements
• Vectors and matrices in MATLAB are indexed from 1.
Specify a single index to
access a vector element.
Specify two indices to
access a matrix element.
>> v = [1 14 34];
>> A = [1 4; 5 6];
>> v(2)
>> A(2,2)
ans =
ans =
14
6
• Slices of vectors and matrices can be obtained by
using the colon notation (start:end)
>> v = [3 4 1 7 8];
>> A = [1 4; 5 6];
>> v(3:5)
>> A(1,:)
ans =
ans =
1
7
8
1
>> A(:,1)
ans =
1
5
Get first row
4
Get first column
10
Vector Operations
Scalar + Vector Operations
• Standard arithmetic operators
with scalars apply the
operator to each element and
the scalar.
Vector + Vector Operations
• Standard arithmetic operators
apply the operator to
corresponding elements.
>> v=[-5 0 2 1];
>> v + 1
ans =
-4
3
2
0
10
5
>> v * 5
ans =
-25
>> v=[-5 0 2 1]; w=[9 1 5 2];
>> v + w
ans =
4
1
7
3
-1
-3
-1
>> v - w
ans =
-14
NB: Vectors must agree in size!
1
Multiply
elements
>> v .* w
ans =
-45
0
10
2
The same rules apply when operators to matrices.
11
Matrix Operations
Matrix Multiplication
• Matrices can be efficiently
multiplied using the *
operator.
>> A = [1 2; 3 4]; B = [5 6; 7 8];
>> A * B
Multiply
matrices not
elements
ans =
19
22
43
50
Matrix Transpose
• To switch the rows and
columns of a matrix, apply
the transpose operator '
• The transpose operator can
be used to convert row/
column vectors.
>> A = [ 1 2; 3 4]
>> a = [1 2 3]
A =
a =
1
2
3
4
>> A'
1
>> a'
ans =
ans =
1
3
1
2
4
2
3
2
3
12
Vector Functions
• MATLAB includes a number of functions for getting basic
statistical information about vectors.
Length of a vector
Range of a vector
Total and average
>> v = [2 0 8 11];
>> min(v)
>> sum(v)
>> length(v)
ans =
ans =
ans =
4
0
21
>> max(v)
>> mean(v)
ans =
ans =
11
• Many built-in functions applicable
to numeric values can also be
applied to vectors and matrices.
• These functions are applied in an
element-wise fashion.
5.2500
>> sqrt(v)
ans =
1.4142
0
2.8284
3.3166
2.0794
2.3979
>> log(v)
ans =
0.6931
-Inf
13
Flow Control
For loops: Iterate over a sequence of values.
• To run a command more than
once as an index varies over a
fixed range:
• We can also change the
increment size:
>> count = 0;
Variable i will
take values
from 1 to 5
>> for i = 1:5
count = count + i;
end
>> count = 0;
>> for i = 1:0.1:5
Variable i will
increment by
0.1 each time
count = count + i;
end
• Alternatively we can iterate
over all the values in a vector:
>> v = [1 4 6];
>> for j = v
count = count + j;
end
14
Flow Control
While loops: Repeatedly
execute a block of code while a
boolean expression holds true.
>> v = 1;
>> while (v <= 10)
v = 2 * v
end
NB: To exit the innermost loop, use the break command
If statements:
Select actions to perform based on a given boolean
expression.
General Format
First branch
>> if i < j
if <condition1>
<block1>
elseif <condition2>
Alternative
branch
<block2>
else
<block3>
end
First condition
x = -1;
elseif i > j
x = 1;
"Last resort"
else
x = 0;
end
15
Strings in MATLAB
• MATLAB strings are formed from
arrays of characters and are
denoted using single quotes.
>> s = 'hello world'
s =
hello world
>> s(1)
h
>> length(s)
11
• Strings can be concatenated
by placing them in a vector,
or using the strcat function.
>> s = ['test' '1234']
s =
test1234
>> strcat('test','1234')
ans =
test1234
• Two strings can be compared
using the strcmp function,
which returns a boolean value.
>> strcmp('test','test')
ans =
1
>> strcmp('test','1234')
ans =
0
16
Console Input/Output
• To simply print a line to the
screen, use the disp function.
• To control precision when
displaying numeric values,
use the format function.
>> disp( 'Hello World' )
Hello World
>> x = 0.23423;
>> format long
>> format short
>> disp(x)
>> disp(x)
0.234230000000000
0.2342
Format string
• For more complex formatting,
use the fprintf function, which
takes a format string similar
to that used in Python.
• The function input allows
the user to provide input
from the keyboard.
>> x = 0.435; y = 3;
>> fprintf('x is %.1f, y is %d\n',x,y)
x is 0.4, y is 3
Prompt
>> r = input('Enter radius: ');
>> a = pi*rˆ2;
>> fprintf('Circle area = %.4f\n', a);
17
Low-Level File Input/Output
• MATLAB has a range of basic
input & output functions for
manually dealing with files.
Description
fopen
Open a file
fclose
Close a file
fgetl
Read a string from a file
fprintf
Write a formatted string to a file
Writing to a file
Reading from a file
File
identifier
Function
Writing
fid = fopen('somefile.txt','r');
x = 0.1;
while 1
fid = fopen('outfile.txt','w');
line = fgetl(fid);
if ~ischar(line)
Reading
fprintf(fid,'%6.2f %12.8f\n',x,exp(x));
fclose(fid);
break
Pass file
identifier to
fprintf!
end
disp(line)
end
fclose(fid);
fprintf(fid,'Exp function\n\n');
Close when
finished
18
High-Level File Input/Output
• Rather than manually formatting and parsing files, MATLAB
has a number of helper functions for easily reading and
writing vectors and matrices to standard file formats.
Read a matrix from a
comma-separated file
using csvread
Write a matrix to a
comma-separated file
using csvwrite
To use an arbitrary
delimiter to separate
values, use dlmread
and dlmwrite
>>> M = csvread('myfile1.csv')
M =
0.2785
0.9575
0.1576
0.9572
0.5469
0.9649
0.9706
0.4854
>>> csvwrite('myfile2.csv', M)
>>> M = dlmread('infile.txt','\t')
M =
0.2785
0.9575
0.1576
0.9572
0.5469
0.9649
0.9706
0.4854
>>> dlmwrite('outfile.txt', M, ':')
19
Script Files
• Scripts are collections of MATLAB commands stored in plain
text files.
• When you type the name of the script file at the MATLAB
prompt the commands in the script file are executed as they
had been typed in from the keyboard.
• Script files end with the extension .m (e.g test.m), and are
sometimes referred to as M-files.
• Script files should be stored where MATLAB can find them
(e.g. in the current directory).
squares.m
Type the name of the
script to run it
>> squares
% A script file to print out squares
1 squared is 1
for i=1:4
2 squared is 4
fprintf('%d squared is %d\n', i, i^2)
end
3 squared is 9
4 squared is 16
20
Writing Functions
• Functions are blocks of code, usually implemented in M-files,
that accept input parameters and return outputs.
• Functions operate on variables within their own workspace. This
workspace is separate from the workspace you access at the
MATLAB command prompt.
• Functions can take zero or more parameters, and return zero or
more values.
General Format
function <return values> = <function_name>( <param1>,<param2>... )
<block of code>
<set return values>
mysum.m
function s = mysum(x,y)
s = x + y;
Set the return value
>> mysum(5,10)
ans =
15
21
Functions - Example
Example function that calculates the sum of the positive
components and the sum of the negative components of
the specified input vector.
sumposneg.m
Return two
values in an
array
function [p,n]=sumposneg(v)
p=0; n=0;
>> v = [-11 5 3 -10];
>> [p,n] = sumposneg(v)
p =
8
for i=1:length(v)
if v(i) > 0
p=p+v(i);
elseif v(i) < 0
n=n+v(i);
end
end
n =
-21
Capture two
returned
values
22
Links and References
• MATLAB Homepage
http://www.mathworks.com/products/matlab/
• Octave Homepage
http://www.gnu.org/software/octave/
• Octave Downloads
http://octave.sourceforge.net/