MATLAB® Fundamentals
MATLAB FUNDAMENTALS &
PROGRAMMING TECHNIQUES
© 2012 MathWorks, Inc.
Pony Lai
support@terasoft.com.tw
MathWorks ...at a Glance
•
Founded in 1984•
Privately held•
Consistently profitable•
Over 2000 employees•
More than 1,000,000 users in over 175 countriesSimulink Product Family Application-Specific Products
MathWorks Product Overview
MATLAB Product Family
Diverse Users
Signal processing
& communications
Utilities & energy
Biotech, medical,
& pharmaceutical
Education Aerospace
& defense
Finance & economics
Government Instrumentation
Automotive
What Can You Do with MATLAB ?
Interactively import, analyze, and export data
Perform calculations and analysis on data sets
01/95 01/00 01/05
2 2.5 3 3.5 4 4.5 5
Date Retail consumption [109 kWh/day]
100 101
10-3 10-2 10-1 100 101 102 103
Period [years]
Power
01/95 01/00 01/05
1.5 2 2.5 3 3.5 4 4.5 5
Date Retail consumption [109 kWh/day]
Data 8-term Model
Create informative data visualizations Write programs to automate complex tasks analysis on data sets
Mexico
Mexico data?
??? Error using ==> gpif at 21 No data for Mexico
No
Yes
19901 1992 1994 1996 1998 2000 2002 2004 2006 2008 1.5
2 2.5
Year
Mexico prices
-102 -100
-98 -96
-94
30 32 34 36 0.07 0.08 0.09 0.1
Lat. Lon.
O3 [ppm]
Course Outline
● Working with the MATLAB User Interface
● Variables and Expressions
● Automating Commands with Scripts
● Automating Commands with Scripts
● Working with Data Files
Course Outline
● Working with the MATLAB User Interface
● Variables and Expressions
● Automating Commands with Scripts
● Automating Commands with Scripts
● Working with Data Files
Outline
• Reading data from file
• Saving and loading variables
• Plotting data
• Plotting data
• Customizing plots
• Calculating statistics and best-fit line
• Exporting graphics for use in other applications
The MATLAB Desktop
Variables (data) in memory Desktop controls
Current folder
memory
Previously entered commands Commands entered
& results returned Files in the
current folder
Customizing the Desktop
Window
actions Resize &
actions Resize &
reposition
Course Example: Gas Price Data
C:\class\coursefiles\mlbe\gasprices
Interactive Importing
Variables in the Base Workspace
19
1990 NaN 1.87 3.63 2.65 4.59 3.16 1 2.05 2.82 1.16 1991 1.96 1.92 3.45 2.9 4.5 3.46 1.3 2.49 3.01 1.14 1992 1.89 1.73 3.56 3.27 4.53 3.58 1.5 2.65 3.06 1.13 1993 1.73 1.57 3.41 3.07 3.68 4.16 1.56 2.88 2.84 1.11 1994 1.84 1.45 3.59 3.52 3.7 4.36 1.48 2.87 2.99 1.11 1995 1.95 1.53 4.26 3.96 4 4.43 1.11 2.94 3.21 1.15 1996 2.12 1.61 4.41 3.94 4.39 3.64 1.25 3.18 3.34 1.23 1997 2.05 1.62 4 3.53 4.07 3.26 1.47 3.34 3.83 1.23 1998 1.63 1.38 3.87 3.34 3.84 2.82 1.49 3.04 4.06 1.06 1999 1.72 1.52 3.85 3.42 3.87 3.27 1.79 3.8 4.29 1.17 2000 1.94 1.86 3.8 3.45 3.77 3.65 2.01 4.18 4.58 1.51 2001 1.71 1.72 3.51 3.4 3.57 3.27 2.2 3.76 4.13 1.46 2002 1.76 1.69 3.62 3.67 3.74 3.15 2.24 3.84 4.16 1.36 2003 2.19 1.99 4.35 4.59 4.53 3.47 2.04 4.11 4.7 1.59 2004 2.72 2.37 4.99 5.24 5.29 3.93 2.03 4.51 5.56 1.88 2005 3.23 2.89 5.46 5.66 5.74 4.28 2.22 5.28 5.97 2.3 2006 3.54 3.26 5.88 6.03 6.1 4.47 2.31 5.92 6.36 2.59 2007 3.85 3.59 6.6 6.88 6.73 4.49 2.4 6.21 7.13 2.8 2008 4.45 4.08 7.51 7.75 7.63 5.74 2.45 5.83 7.42 3.27
11
numeric data “double precision”
The Variable Editor
New Variables
Saving and Loading Variables
Plotting the Data
Automatic codePlot Tools
Axis labels -2 Units -1
4/10 Units -1
Change properties
Select plot components Add plot
elements
Multiple Plots
1
3
2
Formatting the Plot
Data Statistics Tool
Basic Fitting Tool
Exporting to Another Application
Shortcuts
Test Your Knowledge
1. Where does MATLAB display a listing of stored variables and associated attributes?
A. Command Window B. Workspace browser
C. Current Directory browser D. Command History
D. Command History
2. The default MATLAB variable type is:
A. Single B. Double C. Cell
3. T/F: The MATLAB desktop is customizable.
Course Outline
● Working with the MATLAB User Interface
● Variables and Expressions
● Automating Commands with Scripts
● Automating Commands with Scripts
● Working with Data Files
Outline
6 5 4
3 2 1
• Entering commands
• Creating variables & Data Type
• Getting help
9 8 7
6 5
• Getting help 4
• Accessing and modifying values in variables
• Creating character variables
MATLAB Commands
Saving and Loading MAT-Files
save
load
Assignment
>> no_of_penguins = x*sin(pi*t);
1. evaluate right-hand side 2. assign resulting value to
variable on left-hand side create new variable or
overwrite old one, as appropriate
MATLAB Data Types
Array
[full or sparse]
logical char numeric cell structure user
class function handle
Scalar
int8, uint8, int16, uint16, int32, uint32, int64, uint64
single double
abc
Boolean Operating and Indexing
>> Mass = [-2 10 NaN 30 -11 Inf 31];
>> each_pos = Mass>=0 each_pos =
0 1 0 1 0 1 1
>> all_pos = all(Mass>=0) all_pos =
0 Boolean Operators
= = equal to
> greater than
< less than
~= not
0
>> pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin =
0 1 0 1 0 0 1
>> good_mass = Mass(pos_fin) good_mass =
10 30 31
& and
| or isempty()
isfinite(), etc. . . . any()
all()
1 = TRUE 0 = FALSE
>> bool_ops
Integer Arrays
How many colors of truck could you possibly need?
256*256*256
= 16.8 million
double uint8
Creating Vectors
n subdivision points
>> x = [2,3,5,7,11,13];
Arbitrary data
Equally-spaced values
a
n subdivision points
b dx
>> x = a:dx:b;
>> x = linspace(a,b,n);
x
Creating Matrices
>> A = [1,2,3; 4,5,6; 7,8,9];
>> A = [1 2 3; 4 5 6; 7 8 9];
or
or
>> A = [1 2 3 4 5 6
7 8 9]
or
data entry mode
9 8 7
6 5 4
3 2 1
Matrix Creation Functions
companeye
gallery hadamard hankel hilb
invhilb magic ones ones pascal rand randi randn rosser toeplitz vander
wilkinson zeros
B bar
foo 1 2
0 0 1 14
. 3 Cell Arrays
>> A = {pi,[],'foo';...
'bar',eye(2),2;...
[],B,[]};
>> A{2,2}(:,2) ans =
0 1
Construc t
Access
B
Characters and Strings
>> MarkA = 'Friends, Romans, countrymen, lend me your ears';
>> y = x
>> y = 'x'
variable character
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
'F' 'r' 'i' 'e' 'n' 'd' 's' ',' ' ' 'R' 'o' 'm' 'a' 'n' 's' ',' ' ' 'c'
1-by-46 char array
>> FriendNationality = MarkA(10:15)
Fields
MyWhale
fundamental frequency amplitude
175 2
name Mushu
Structures
Fields
[x,t] = callmodel_fun_s(MyWhale);
decay rate 1.5
modulation frequency number of harmonics
0.65 3
aquarium(3)
fundamental frequency amplitude
decay rate
165
1 0.8
name Shamu
aquarium(2)
name Willy
>> aquarium aquarium =
1x3 struct array with fields:
name
fundamentalfreq amplitude
decayrate
modulationfreq harmonics
Structure Arrays
decay rate 0.8
modulation frequency number of harmonics
1.0 4
fundamental frequency amplitude
decay rate
180
2.5 1.9
modulation frequency number of harmonics
0.5 5
aquarium(1)
fundamental frequency amplitude
decay rate
175
2 1.5
name Mushu
modulation frequency number of harmonics
0.65 3
aquarium(3)
fundamental frequency amplitude
decay rate
165
1 0.8
name Shamu
aquarium(2)
name Willy
Indexing into Structure Arrays
>> aquarium(2)
>> aquarium.amplitude
decay rate 0.8
modulation frequency number of harmonics
1.0 4
fundamental frequency amplitude
decay rate
180
2.5 1.9
modulation frequency number of harmonics
0.5 5
aquarium(1)
fundamental frequency amplitude
decay rate
175
2 1.5
name Mushu
modulation frequency number of harmonics
0.65 3
>> aquarium(2).amplitude
>> aquarium.amplitude
Help and Documentation
search browse
help doc
docsearch
Row, Column Indexing
>> gasprices(1,2) >> gasprices(3,6) >> gasprices(2,end)
>> gasprices(end,2) >> gasprices(end,end)
Multiple Row, Column Indices
>> Year = gasprices(:,1) >> gasprices([3,4],6:9)
>> gp08 = gasprices(end,2:end)
Indexed Assignment
>> x = gasprices(1,2)
reference
>> x = 1.96;
>> gasprices(1,2) = x
assignment
Concatenation
>> A A =
1 2 3 4 5 6 7 8 9
>> C = [A,B]
C =
1 2 3 1 0 0 4 5 6 0 1 0 7 8 9 0 0 1
>> B B =
1 0 0 0 1 0 0 0 1
>> D = [A;B]
D =
1 2 3 4 5 6 7 8 9 1 0 0 0 1 0 0 0 1
[]
Test Your Knowledge
1. (Select all that apply) Which of the following will create a matrix with three rows?
A. A = [zeros(2,4);ones(1,4)];
B. A = [1;2;3,4;5;6];
C. A = [1,2;3,4;5,6]';
C. A = [1,2;3,4;5,6]';
D. A = rand(3);
2. Given a 5-by-5 matrix A, A(4:end,3:4) will produce a matrix of what size?
A. 1-by-2 B. 2-by-2 C. 2-by-3 D. 3-by-2
Course Outline
● Working with the MATLAB User Interface
● Variables and Expressions
● Automating Commands with Scripts
● Automating Commands with Scripts
● Working with Data Files
Outline
• A modeling example
• The Command History
• Creating script files
• Creating script files
• Running scripts
• Code sections
• Publishing scripts
Course Example: Modeling a Whal Call
Sum of harmonics of a fundamental frequency Amplitude modulated: y(t) = A(t)y0(t)
= ∑
n
t nf t
y
0( ) sin( 2 π
0)
e
) 2
sin(
)
(t A0e f t
A = −Bt π m
Decaying oscillation
The Command History
The MATLAB Editor
edit% CALLMODEL Models a blue whale B call.
%
% Uses a model of the form y = A.*y0
% where A = A0*exp(-B*t).*sin(2*pi*fm*t)
% and y0 is a sum of harmonics
% yn = sin(2*pi*n*f0*t)
% Create the time base for the signal.
Script Files
H1 line
Help
% Create the time base for the signal.
fs = 4000;
t = 0:(1/fs):1.5;
% Set the fundamental frequency of the call.
f0 = 175;
% Create the harmonics.
y0 = sin(2*pi*f0*t) + sin(2*pi*2*f0*t) + sin(2*pi*3*f0*t);
Comments Code
callmodel.m
Running a Script
Code Sections
Create the time base for the signal
Set the fundamental frequency of the call
Create the
%%
%%
Create the harmonics
Create the envelope
Create the call
Plot the model call and listen to it
Publishing Code
Word®
Test Your Knowledge
1. T/F: Anything following a % sign is ignored by MATLAB as a comment.
2. T/F: With code sections, you can modify your code and rerun it without having to save the file.
it without having to save the file.
3. T/F: MATLAB uses all the comment lines up to the first line of code as help for your script file.
4. T/F: Script files can access and modify any variables already in the base MATLAB workspace.
Course Outline
● Working with the MATLAB User Interface
● Variables and Expressions
● Automating Commands with Scripts
● Automating Commands with Scripts
● Working with Data Files
Outline
• File types and file formats
• Fixed-structure files
• Spreadsheets and
• Spreadsheets and delimited text files
• Low-level file I/O
File Types and File Formats
Audio Video Image
Scientific data
File Type File Format
BMP GIF JPEG PNG
Predefined structure
Scientific data Geographic data
…
Spreadsheet Delimited text
PNG
…
XLS CSV TXT
Flexible structure
???
Reading and Writing Fixed-Structure Files
audioread cdfread csvread dlmread
data = xyzread('file.xyz')
h5read imread ncread urlread xmlread ...
xyzwrite(data,'file.xyz')
Interactively Importing Text Files
and Spreadsheets
Exporting Spreadsheets
xlswrite
csvwrite csvwrite
dlmwrite
Read and Write data from EXCEL
XLSREAD
– num = xlsread('filename')
– num = xlsread('filename', -1)
– num = xlsread('filename', 'sheet') – num = xlsread('filename', 'range') – [num, txt] = xlsread('filename',
'sheet', 'range')
XLSWRITE
– xlswrite('filename', M)
– xlswrite('filename', M, 'sheet') – xlswrite('filename', M, 'range') – xlswrite('filename', M, 'sheet',
'range')
Test Your Knowledge
1. (Select all that apply) Which of the following can you change when importing a delimited text file with the Import Tool?
A. Which columns to import.
B. The format (text, number, date, etc.) of each column.
C. The delimiter character.
C. The delimiter character.
D. How to import missing values.
2. Suppose “ABC” is a supported format in MATLAB. Which command would import data from an ABC file mydata.abc into a matrix A?
A. mydata = abcread(A);
B. abcread(A,mydata);
C. abcread('mydata.abc',A);
D. A = abcread('mydata.abc');
E. A = abcread(mydata);