Professional Documents
Culture Documents
INTRODUCTION
to the use of MATLAB
L. Savoldi, R. Bonifetto
Dipartimento Energia
Content
1.
2.
3.
4.
An introduction to MATLAB
The MATLAB interfaces
Variables, vectors and matrices
Using operators
1. Introduction to MATLAB
What is MATLAB?
Dipartimento Energia
1. MATLAB Functionality
Built-in Functionality includes
Dipartimento Energia
1. MATLAB paradigm
MATLAB is an interactive environment
Commands are interpreted one line at a time
Commands may be scripted to create your own functions or
procedures
Dipartimento Energia
Dipartimento Energia
To stop (nicely)
Select File
Dipartimento Energia
Workspace
Command Window
Command History
7
1. Window Components
Dipartimento Energia
Dipartimento Energia
1. The .m files
Dipartimento Energia
mickey.m
Dipartimento Energia
11
Value
This is the data the is associated to the variable; the data is accessed
by using the name.
12
Dipartimento Energia
>> A = 32
13
Dipartimento Energia
>> B = A
14
Dipartimento Energia
>> A = 10
>> A + A
15
2.1 Vectors
A vector is a list of numbers
Dipartimento Energia
16
2.1 Vectors
Dipartimento Energia
17
2.1 Vectors
Dipartimento Energia
18
Dipartimento Energia
2.1 Vectors
Different ways to assign a vector:
By listing components
vector = [2,3,4,5,6,7,8];
By assigning a rule:
vector = [2:8];
with the instruction linspace:
vector = linspace(2,8,7);
2.1 Matrices
A MATLAB matrix is a rectangular array of numbers
Dipartimento Energia
2.1 Matrices
You can create matrices (arrays) of any size using a
combination of the methods for creating vectors
Dipartimento Energia
21
2.1 Matrices
You can also use built in functions to create a matrix
>> A = zeros(2, 4)
creates a matrix called A with 2 rows and 4 columns containing the
value 0
>> A = zeros(5) or >> A = zeros(5, 5)
creates a matrix called A with 5 rows and 5 columns
Dipartimento Energia
22
23
24
Excel
2nd
Dipartimento Energia
2nd
MATLAB
1st
25
Dipartimento Energia
>> results(3, 4) = 10
or
>> results(3,4) = results(3,4) * 100
26
Dipartimento Energia
27
Dipartimento Energia
28
Dipartimento Energia
>> results(:, 3) = 0
29
Dipartimento Energia
NOTE: Unless you are overwriting with a single value the data entered must
be of the same size as the matrix part to be overwritten.
30
Dipartimento Energia
Multiple Rows:
>> Variable_Name(start:end, :)
Multiple Columns:
>> Variable_Name(:, start:end)
31
Dipartimento Energia
Multiple Columns:
>>Variable_Name(:, [index1, index2, etc.])
32
Dipartimento Energia
>> results([3,6], :) = 0
>> results(3:6, :) = 0
33
Dipartimento Energia
Dipartimento Energia
Double click on the variable you would like to store the data in
This will open the array editor
In the Array Editor right click in the first element and select
Paste Excel Data
35
Dipartimento Energia
36
Dipartimento Energia
[start:stepsize:end]
>> [11:2:21]
11
13
>>
15
17
19
21
17.86
15.79
13.72
11.65
Dipartimento Energia
2.4 Concatenation
The square brackets [] are the concatenation operator.
So far, we have concatenated single elements to form a
vector or matrix.
The operator is more general than that for example we
can concatenate matrices (with the same dimension) to
form a larger matrix
Dipartimento Energia
39
Some exercises...
Assign in an array-smart form the matrix:
Dipartimento Energia
Dipartimento Energia
3. More Operators
41
Dipartimento Energia
Add: +
Subtract: Divide: ./
Multiply: .*
Power: .^ (e.g. .^2 means squared)
Dipartimento Energia
MATLAB:
>> C = A + B
>> C = (A + 10) ./ 2
43
Dipartimento Energia
E.g.
>> data = rand(5,1)
>> A = 10
>> results = data + A
44
Dipartimento Energia
45
Dipartimento Energia
NOTE: There is a simpler way to do this using the Sum and Prod functions,
this will be shown later.
46
Dipartimento Energia
47
Dipartimento Energia
Matrix Multiply: *
Matrix Right Division: /
Example:
48
Dipartimento Energia
Dipartimento Energia
Logical Operators:
50
Dipartimento Energia
ind is the same size as r and contains zeros (false) where the data does not
fit the criteria and ones (true) where it does, this is called a Logical Vector.
r(ind) then extracts the data where ones exist in ind
Use of find(condition)
51
Dipartimento Energia
>> r(ind)
52
Dipartimento Energia
53
Dipartimento Energia
>> r = results(:,1)
>> ind = r > 0.2 & r <= 0.9
>> r(ind)
>> (x<0)*1
Returns
1 if x is negative
0 if x is positive
Equal condition is written ==
More later...
54
Some exercises...
Dipartimento Energia
4 Functions
A function performs an operation on the input variable
you pass to it
Passing variables is easy, you just list them within round
brackets when you call the function
Dipartimento Energia
function_Name(input)
56
4 Functions
The result of the function can be stored in a variable
Dipartimento Energia
You can also tell the function to store the result in parts of a
matrix
>> matrix(:, 5) = function_Name(matrix(:, 1:4))
57
4 Functions
To get help with using a function enter
>> help function_Name
Dipartimento Energia
58
Dipartimento Energia
4 Functions
MATLAB has many built in functions which make it easy to perform a variety of
statistical operations
sum Sums the content of the variable passed
prod Multiplies the content of the variable passed
mean Calculates the mean of the variable passed
median Calculates the median of the variable passed
mode Calculates the Mode of the variable passed
std Calculates the standard deviation of the variable passed
sqrt Calculates the square root of the variable passed
max Finds the maximum of the data
min Finds the minimum of the data
size Gives the size of the variable passed
sort Sorts the vector in increasing or decreasing order
unique Sorts the vector in increasing or decreasing order removing
duplicate elements
find(condition) Returns the location of the array elements satisfying the
logical condition
rand Returns random real numbers between 0 and 1
round, floor, ceil Rounds to the closest integer number
59
4 Special functions
There are a number of special functions that provide
useful constants
Dipartimento Energia
pi
= 3.14159265.
i or j = square root of -1
Inf
= infinity
NaN
= not a number
4 Functions
Passing a vector to a function like sum, mean, std will
calculate the property within the vector
Dipartimento Energia
>> sum([1,2,3,4,5])
= 15
>> mean([1,2,3,4,5])
=3
61
4 Functions
Dipartimento Energia
62
4 Functions
To change the direction of the calculation to the other
dimension (columns) use:
>> function_Name(input, 2)
Dipartimento Energia
63
4 Functions
From Earlier
>> results(:, 5) = results(:, 1) + results(:, 2) + results(:, 3) + results(:, 4)
or
>> results(:, 5) = results(:, 1) .* results(:, 2) .* results(:, 3) .* results(:, 4)
Dipartimento Energia
64
4 Functions
Dipartimento Energia
65
4 Functions
You can find the maximum and minimum of some data
using the max and min functions
Dipartimento Energia
>> max(results)
>> min(results)
66
4 Functions
We can use functions and logical indexing to extract all the results
for a subject that fall between 2 standard deviations of the mean
Dipartimento Energia
>> r = results(:,1)
>> ind = (r > mean(r) 2*std(r)) & (r < mean(r) + 2*std(r))
>> r(ind)
67
4 Building functions
Particular type of script files, starting with the
keyword
function
Inputs
Dipartimento Energia
Outputs
function
[<out1>,...,<outn>]=<functionname>(<in1>,...,<inn>)
% Function help content
<body of the function>
<out1>=...;
<outn>=...;
end
68
4 Building functions
Call to a function:
[<OUT1>,...,<OUTn>]=<functionname>(<IN1>,...,<I
Nn>);
Dipartimento Energia
4 Building functions
Functions can be used if:
Dipartimento Energia
4 Building functions
1) Define the function as an instruction in the script:
a) fun='1./(1+x.^2);
b) fun=inline('1./(1+x.^2)', 'x');
c) fun=@(x)[1./(1+x.^2)]; %(anonymous function)
Dipartimento Energia
4 Building functions
Dipartimento Energia
72
5 Plotting
The plot function can be used in different ways:
>> plot(data)
>> plot(x, y)
>> plot(data, r.-)
Dipartimento Energia
73
5 Plotting
A basic plot
>> x = [0:0.1:2*pi]
>> y = sin(x)
>> plot(x, y, r.-)
1
0.8
0.6
0.4
0.2
Dipartimento Energia
0
-0.2
-0.4
-0.6
-0.8
-1
74
5 Plotting
Plotting a matrix
MATLAB will treat each column as a different set of data
0.9
0.8
0.7
Dipartimento Energia
0.6
0.5
0.4
0.3
0.2
0.1
10
75
5 Plotting
Dipartimento Energia
76
5 Plotting
>> x = [0:0.1:2*pi];
>> y = sin(x);
Sin Plots
2
1.5
>> hold on
Dipartimento Energia
1
0.5
sin(x)
2*sin(x)
-0.5
>> xlabel(x);
-1.5
>> ylabel(y);
-2
3
x
77
5 Plotting
Plotting data
0.9
0.8
0.7
Dipartimento Energia
0.6
0.5
0.4
0.3
0.2
0.1
10
78
5 Plotting
Error bar plot
>> errorbar(mean(data, Mean
2),teststd(data,
[], 2))
results with error bars
1
0.9
0.8
Dipartimento Energia
0.7
0.6
0.5
0.4
0.3
0.2
0.1
10
12
79
5 Plotting
Dipartimento Energia
You can close all the current plots using close all
80
Dipartimento Energia
81
Dipartimento Energia
Not only
in
Matlab!
Conditions
Boolean statements
(x<0)*1
Returns
Dipartimento Energia
1 if x is negative
0 if x is positive
If statements
if (<condition1>)
<actions1>
elseif (<condition2>)
<actions2>
else
<actions3>
end
83
Loops
Dipartimento Energia
For loops
for (<condition>)
<actions>
end
While loops
while (<condition>)
<actions>
end
Do not use single character variables:
counter ii and not i
84
Loop breakers
Dipartimento Energia
break
stops the execution of the loop; after this statement is
passed, the first line after the end of the loop will be
executed
return
stops the execution of the script; after this statement
is passed, the first line after the call to the function (or
script) will be executed
The use of these two commands makes the debug and
error tracing much difficult: they can always be
substituted by if - else statements and this option is
to be preferred in all codes
85
Dipartimento Energia
eval(<string>);
executes the string as if it were a code line
Allows flexible operations in loops
Use of
cd <directorypath>
to move to folder in directorypath
cd ..
to move one folder up
See folder use_eval (Matlab session)
86
Debug (I)
If an error stops the computation, detailed error report
is provided in Matlab command prompt in red
characters
It allows the full mapping of the error as it shows the
line containing the error also inside nested function
Dipartimento Energia
87
Debug (II)
It is possible to run a Matlab script in Debug
mode; it allows to
Dipartimento Energia
Dipartimento Energia
plot(<xx>,<yy>);
OK!
Useless figure!
89
Handles
Handles are used to set or get values for object properties
set(<handle>,<propertyname>,<propertyvalue>);
get(<handle>,<propertyname>);
Dipartimento Energia
Example:
H1=plot(time,pressure);
set(H1,color,g);
gca: graphical current axis
gcf: graphical current figure
90
Other plots
subplot(<row>,<column>,<number>)
loglog(<xx>,<yy>);
semilogx(<xx>,<yy>) and semilogy(<xx>,<yy>);
Dipartimento Energia
errorbar(<xx>,<yy>,<ye->,<ye+>);
bar(<array>);
polar(,r);
Dipartimento Energia
plotyy(<xx1>,<yy1>, <xx2>,<yy2>);
Useless figure!
OK!
.fig
Matlab figure files (editable)
Dipartimento Energia
.eps
Figure files (to be read with GhostView free
software)
.mat
Complex (structured) data files
.dat, .txt
Data files
Special commands
<inputvalue>=input(<variablename> = ');
waits for the user to type a value for variable
variablename to be assigned to inputvalue
Execute cmd statements:
!del <filename>.<extension>
Dipartimento Energia
!<file1>.bat
!<file2>.exe
executes the 2 .bat (or .exe) files sequentially
!<file1>.bat &
!<file2>.exe &
executes the 2 .bat (or .exe) files in 2 different parallel windows
94