Matlab: Historical Overview
Matlab: Historical Overview
Matlab: Historical Overview
MATLAB
Overview
http://www.mathworks.com/company/newsletters/news_notes/clevescorner/dec04.html
Overview
MATLAB is a high-performance language for technical
computing. It integrates computation, visualization, and
programming in an easy-to-use environment where
problems and solutions are expressed in familiar
mathematical notation. Typical uses include
Math and computation
Algorithm development
Data acquisition
Modeling, simulation, and prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
Application development, including graphical user
interface building
Overview (cont.)
MATLAB features a family of add-on applicationspecific solutions called toolboxes. Very
important to most users of MATLAB, toolboxes
allow you to learn and apply specialized
technology. Toolboxes are comprehensive
collections of MATLAB functions (M-files) that
extend the MATLAB environment to solve
particular classes of problems. Areas in which
toolboxes are available include signal
processing, control systems, neural networks,
fuzzy logic, wavelets, simulation, and many
others.
Overview (cont.)
MATLAB is an interactive system whose basic data
element is an array that does not require dimensioning.
This allows you to solve many technical computing
problems, especially those with matrix and vector
formulations, in a fraction of the time it would take to
write a program in a scalar noninteractive language such
as C or Fortran.
MATLAB has evolved over a period of years with input
from many users. In university environments, it is the
standard instructional tool for introductory and advanced
courses in mathematics, engineering, and science. In
industry, MATLAB is the tool of choice for highproductivity research, development, and analysis.
Graphics
MATLAB has extensive facilities for displaying
vectors and matrices as graphs, as well as
annotating and printing these graphs. It includes
high-level functions for two-dimensional and
three-dimensional data visualization, image
processing, animation, and presentation
graphics. It also includes low-level functions that
allow you to fully customize the appearance of
graphics as well as to build complete graphical
user interfaces on your MATLAB applications.
Line
Graphs
Bar
Graphs
Area
Graphs
Direction
Graphs
Radial
Graphs
plot
bar (grouped)
area
feather
polar
plotyy
barh (grouped)
pie
quiver
rose
surf
quiver3
scatter3
contour3
surfl
comet3
coneplot
Limitations
Proprietary product subject users to a vendor
lock-in
The language has a mixed heritage which can
cause erratic syntax.
MATLAB uses parentheses, e.g. y = f (x), for both
indexing into an array and calling a function.
Using Matlab
Working with Matrices
Using Matlab
Using Matlab
c = 5.66 or c = [5.66]
c = 5.66 or c = [5.66]
x = [ 3.5, 33.22, 24.5 ]
c is a scalar or a 1 x 1 matrix
c is a scalar or a 1 x 1 matrix
x is a row vector or a 1 x 3 matrix
Using Matlab
Using Matlab
c = 5.66 or c = [5.66]
x = [ 3.5, 33.22, 24.5 ]
x1 = [ 2
5
3
-1]
c = 5.66 or c = [5.66]
x = [ 3.5, 33.22, 24.5 ]
x1 = [ 2
5
3
-1]
A=[1 2 4
2 -2 2
0 3 5
5 4 9]
c is a scalar or a 1 x 1 matrix
x is a row vector or a 1 x 3 matrix
Using Matlab
c is a scalar or a 1 x 1 matrix
x is a row vector or a 1 x 3 matrix
A is a 4 x 3 matrix
Using Matlab
Using Matlab
Using Matlab
Indexing Matrices
Using Matlab
Using Matlab
Indexing Matrices
Indexing Matrices
Using Matlab
Using Matlab
Data Types and Formats
Matrix Shortcuts
The ones and zeros functions can be used to create any m x n
matrices composed entirely of ones or zeros
Example
a = ones(2,3)
a = [1 1
11
1 1]
b = zeros(1,5)
b = [0 0 0 0 0]
who
whos
Using Matlab
Saving your Work
To save data to a *.mat file:
Typing save filename at the >> prompt and the file
filename.mat will be saved to the working directory
Select Save from the file pull down menu
To reload a *.mat file
1. Type load filename at the >> prompt to load
filename.mat
(ensure the filename is located in the current working
directory)
2. Select Open from the file pull down menu and
manually find the datafile
Exercises
Enter the following Matrices in matlab using spaces,
commas, and semicolons to separate rows and
columns:
1 21 6
A = 5 17 9
31 2 7
4
22
C=
16
160
B = [1 64 122 78 38 55]
D = [65]
D=
8 41 166 42
55 28 16 2
1 12
0 0
25 65 24 19
E = a 5 x 9 matrix of 1s
Exercises
Exercises
31 2 7
4
22
C=
16
160
B = [1 64 122 78 38 55]
D = [65]
D=
8 41 166 42
55 28 16 2
1 12
0 0
25 65 24 19
E = a 5 x 9 matrix of 1s
2 7
31 0
4
22
C=
16
76
160
0 38 55]
64 122 78
B = [1 76
D = [65]
D=
8
55
76
25
41 166 42
16
2
0
0
1 12
65 24 76
19
28
E = a 5 x 9 matrix of 1s
Matrix Operations
Indexing Matrices
An empty or null matrix can be created using square brackets
>> A = [ ]
B. Matrix Operations
** TIP: The size and length functions can quickly return the number
of elements and dimensions of a matrix variable
Matrix Operations
Matrix Operations
Indexing Matrices
Indexing Matrices
A = [1 2 4 5
6 3 8 2]
A = [1 2 4 5
6 3 8 2]
>> A(:,3) = [ ]
A = [1 2 5
6 3 2]
>> A(1,3) = [ ]
??? Subscripted assignment dimension mismatch.
>> A(2,:) = [ ]
A = [1 2 5]
N Dimensional Matrices
A = [1 2 4 5
6 3 8 2]
B = [5 3 7 9
1 9 9 8]
N Dimensional Matrices
Examples
A = [1 2 4 5
6 3 8 2]
B = [5 3 7 9
1 9 9 8]
>> C = cat(3,[1,2,4,5;6,3,8,2],[5,3,7,9;1,9,9,8])
>> C = cat(3,A,B)
CAT(2,A,B) is the same as [A,B]. (i.e. concatenate rows)
CAT(1,A,B) is the same as [A;B]. (i.e. concatenate columns)
Matrix Operations
Matrix Operations
Scalar Operations
Scalar Operations
A = [1 2 4 5
6 3 8 2]
B = [1 C = 5
7
3
3]
Try:
A + 10
A*5
B/2
A^C
Matrix Operations
Matrix Operations
Scalar Operations
Matrix Operations
A = [1 2 4 5
6 3 8 2]
Try:
A + 10
A*5
B/2
A^C
B = [1 C = 5
7
3
3]
Try:
>>A + B
B = [1 C = 5
7
3
3]
>>A + C
>>A + D
D = [2 4 6 8
1 3 5 7]
Matrix Operations
Matrix Operations
Matrix Multiplication
The dot product for two matrices A and B is defined whenever the
number of columns of A are equal to the number of rows of b
Matrix Operations
A(x1,y1) * B(x2,y2)
Matrix Operations
The dot product for two matrices A and B is defined whenever the
number of columns of A are equal to the number of rows of b
The dot product for two matrices A and B is defined whenever the
number of columns of A are equal to the number of rows of b
A(x1,y1) * B(x2,y2)
A(x1,y1) * B(x2,y2)
Matrix Operations
The Dot Product
Matrix Operations
The Dot Product
A(x1,y1) * B(x2,y2) = C(x1,y2)
The dot product for two matrices A and B is defined whenever the
number of columns of A are equal to the number of rows of b
A = [1 2
6 3]
B = [1
7
3
3]
D = [2 2 E = [2 4 3 6]
2 2]
Try:
>>A * D
>>B * E
>>A * B
Matrix Operations
Matrix Operations
Matrix Division
A = [1 2
63]
>>A .* D
Ans = [ 2 4
12 6]
B = [1
7
3
3]
D = [2 2 E = [2 4 3 6]
22]
Matrix Operations
Matrix Operations
A = [1 2 4 5
6 3 8 2]
B = [1
7
3
3]
D = [2 2 2 2 E = [2 4 3 6]
2 2 2 2]
>>A ./ D
Ans = [ 0.5000
3.0000
Matrix Operations
1.0000
1.5000
2.0000
4.0000
2.5000
1.0000 ]
Matrix Operations
Matrix Exponents
Matrix Operations
Matrix Operations
Shortcut: Transposing Matrices
inv()
det()
poly()
kron()
A = [1 2 4 5
6 3 8 2]
Matrix inverse
Matrix determinant
Characteristic Polynomial
Kronecker tensor product
>> B
B = [1 7 3 3]
Relational Operators
Relational operators are used to compare two scaler values or
matrices of equal dimensions
C. Relational Operators
Relational Operators
<
less than
<=
less than or equal to
>
Greater than
>=
Greater than or equal to
==
equal
~=
not equal
Relational Operators
Comparison occurs between pairs of corresponding elements
A 1 or 0 is returned for each comparison indicating TRUE or
FALSE
Matrix dimensions must be equal!
>> 5 == 5
Ans 1
>> 20 >= 15
Ans 1
Relational Operators
A = [1 2 4 5
6 3 8 2]
C = [2 2 2 2
2 2 2 2]
Try:
>>A > B
>> A < C
Relational Operators
The Find Function
B=7
Relational Operators
The Find Function
A = [1 2 4 5
6 3 8 2]
B=7
C = [2 2 2 2
2 2 2 2]
D = [0 2 0 5 0 2]
The find function can also return the row and column indexes of
of matching elements by specifying row and column arguments
>> [x,y] = find(A == 5)
D = [10 2 10 5 10 2]
>> A(x,y) = 10
A = [ 1 2 4 10
6382 ]
Matrix Operations
Matrix Operations
Embedding Functions
Embedding Functions
A = [1 2 4 5
6 3 8 2]
A = [1 2 4 5
6 3 8 2]
B=2
C = [2 2 2 2
2 2 2 2]
D = [0 2 0 3 0 2]
>> D(find(D>0))
Ans 2 3 2
B=2
C = [2 2 2 2
2 2 2 2]
D = [0 2 0 3 0 2]
>> D(find(D>0))
Ans 2 3 2
>>D(D(find(D>0)))
Ans 2 0 0
Matrix Operations
Embedding Functions
Functions may be embedded into other functions, i.e. the values
sent to a function can be the result from some other function.
Function embedding can be many levels deep
Many lines of code can be condensed into one single command
A = [1 2 4 5
6 3 8 2]
B=2
>> D(find(D>0))
Ans 2 3 2
>>D(D(find(D>0)))
Ans 2 0 0
>>A(B, D(find(D>0)) )
Ans 3 8 3
C = [2 2 2 2
2 2 2 2]
D = [0 2 0 3 0 2]
B. Multiple Command
Execution
Programming Tricks
Programming Tricks
Programming Tricks
Programming Tricks
Matlab Scripts
Entering Multiple Lines Without Running Them
Matlab Scripts
Advantages of M-files
Easy editing and saving of work
Undo changes
Readability/Portability - non executable comments can be
added using the % symbol to make make commands easier to
understand
Saving M-files is far more memory efficient than saving a
workspace
Logical Operators
Logical Operators
Logical Operators
&
AND
|
OR
~
NOT
A&B=?
Logical Operators
Logical Operators
&
AND
|
OR
~
NOT
A|B=?
A
1
1
0
0
B
1
0
1
0
Result
1
0
0
0
Logical Operators
B
1
0
1
0
Result
1
1
1
0
Logical Operators
Examples:
Logical Operators
&
AND
|
OR
~
NOT
~A = ?
~B = ?
A
1
1
0
0
A ~A
1 0
0 1
B ~B
1 0
0 1
A=0
B = false C = 1
D=8
E = true
F=[0102
0 3 0 1]
Try:
>>A & B
>>A & C
>>A & D
>>A & E
>>A & F
>>A | B
>>A | C
>>A | D
>>A | E
>>A | F
>> ~A
>> ~B
>> ~C
>> ~D
>> ~E
>> ~F
>> ~A&C
>> ~C & F
Logical Operators
Examples:
Logical Operators
Examples:
A=0
B = false
F=[0102
0 3 0 1]
C=1
D=8
E = true
>>A & B = 0
>>A & C = 0
>>A & D = 0 >>A & E = 0
>>A & F = [0 0 0 0 >>A | B = 0
>>A | C = 1
0 0 0 0] >>A | D = 1 >>A | E = 1
>>A | F = [0 1 0 1
0 1 0 1]
Logical Operators
A=0
B = false
F=[0102
0 3 0 1]
C=1
D=8
E = true
>> ~A = 1
>> ~B = 1
>> ~C = 0
>> ~D = 0
>> ~E = 0
>> ~F =[1 0 1 0
>> ~A&C = 1 >> ~C & F = [0 0 0 0
1 0 1 0]
0 0 0 0]
**When performing a boolean operation with a matrix, an
element by element boolean comparison is made
Logical Operators
Order of Precedence:
Order of Precedence:
A&B|C = (A&B) | C
A|B&C = A | (B&C)
A&B|C = (A&B) | C
A|B&C = A | (B&C)
A&~B|C = (A&(~B)) | C
A|~B&C = A | ((~B)&C)
Condition Statements
It is often necessary to only perform matlab
operations when certain conditions are met
Relational and Logical operators are used to define
specific conditions
Simple flow control in matlab is performed with the If,
Else, Elseif and Switch statements
Condition Statements
If, Else, and Elseif
An if statement evaluates a logical expression and evaluates a
group of commands when the logical expression is true
The list of conditional commands are terminated by the end
statement
If the logical expression is false, all the conditional commands
are skipped
Execution of the script resumes after the end statement
Basic form:
if logical_expression
commands
end
Condition Statements
Example
A=6
B=0
if A > 6
D = [1 2 6]
A=A+1
end
if A | B
E = mean(B)
end
Condition Statements
If, Else, and Elseif
The else statement forces execution of the commands below the
else statement if the original logical expression evaluates to false
Only one list of commands can be executed
Basic form:
if logical_expression
commands 1
else
commands 2
end
Condition Statements
Example
A=6
B=0
Condition Statements
Condition Statements
Example
A=6
Basic form:
if logical_expression
commands 1
elseif logical_expression_2
commands 2
elseif logical_expression_3
commands 3
end
if A & B
E = mean(B)
else
E=0
end
if A > 6
D = [1 2 6]
A=A+1
else
D = [ 0 0 0]
A=A-1
end
B=0
if A > 3
D = [1 2 6]
A=A+1
elseif A > 2
D=D+1
A=A+2
end
** Both the if and elseif statements are evaluated
Condition Statements
Condition Statements
Example
Switch
The switch statement can act as many elseif statements
Only the one case statement whos value satisfies the original
expression is evaluated
Basic form:
switch expression (scalar or string)
case value 1
commands 1
case value 2
commands 2
case value n
commands n
end
A=6
B=0
switch A
case 4
D = [ 0 0 0]
A=A-1
case 5
B=1
case 6
D = [1 2 6]
A=A+1
end
** Only case 6 is evaluated
Loops
Loops
For Loops
Loops
Loops
For Loops
For Loops
Examples:
for i = 1:1:100
x(i) = 0
end
Assigns 0 to the first 100 elements of vector x
If x does not exist or has fewer than 100 elements,
additional space will be automatically allocated
Loops
A=[]
for i = 1:m
for j = 1:n
A(i,j) = i + j
end
end
Creates an m by n matrix A whose elements are the
sum of their matrix position
While Loops
Loops
While Loops
The while loop executes a statement or group of
statements repeatedly as long as the controlling
expression is true
Basic Form:
while expression
statements
end
Examples:
A = 6 B = 15
while A > 0 & B < 10
A=A+1
B=B2
end
Iteratively increase A and decrease B until the two
conditions of the while loop are met
** Be very careful to ensure that your while loop will
eventually reach its termination condition to prevent
an infinite loop
Loops
While Loops
Loops
Breaking out of loops
Examples:
A=6
B = 15
while A > 0 & B < 10
if A < 0
A=A+1
elseif B > 10
B=B2
end
end
Conditional statements can be nested for specific
internal control of variables
Loops
Functions in Matlab
function outargs=funcname(inargs);
input
Function
output
Simple Example
Find the cube of a number -> (x3)
Type the code below into an .m file and save it
as cube.m
Set the Matlab directory appropriately
In Matlab window, type cube(3), is the result
correct?
Now you have a reusable function that can
calculate the cube of any number
function [y] = cube(x)
y = x*x*x;
>> cube(3)
Ans = 125
>> cube 1.75
Ans = 5.3594
>> cube(2,3)
Ans = 8 ???
>> [a b] = cube(2,3)
a=8
b = 27
nargin
Matlab will accept a function call with any
number of inputs and outputs
nargin can be used to find out how many
inputs the user has provided
It is automatically passed with the function
function [y1, y2] = cube(x1, x2)
if nargin == 1
y1 = x1*x1*x1;
y2 = nan;
elseif nargin == 2
y1 = x1*x1*x1;
y2 = x2*x2*x2;
end
>> cube(2,3)
Ans = 8
>> [a b] = cube(2,3)
a=8
b = 27
return
return terminates computation of the
function and returns whatever is calculated
thus far
function [y1, y2] = cube(x1, x2)
if nargin == 1
y1 = x1*x1*x1;
y2 = nan;
return
end
>> cube(2,3)
Ans = 8
>> [a b] = cube(2,3)
a=8
b = 27
y1 = x1*x1*x1;
y2 = x2*x2*x2;
Mini-Project
Lets combine what we have learned thus
far in the course
Loops, If Statements, Functions
Basic Matlab Operators
>> cube(2)
Ans = 8
Mini-Project
Raising any number of numbers to the nth power
Inputs:
A vector of numbers to be raised (N1Nm)
A vector of powers (P1Pm)
Outputs:
A vector of raised values (N1P1 NmPm)
An error flag: 1 if error in calculation, 0 if successful
Caveats:
If only one input is provided, the function should square each
entry, so output = (N12Nm2) and error flag is 0
If the length of N and P are not the same, this is an error, return
anything in the output vector and a 1 in the error flag
Mini-Project
Solution 1
(simple)
Solution 2
Importing Data
y = ones(1,length(x));
if nargin == 1
[y e] = raise(x,2*ones(1,length(x)));
return
elseif nargin == 2
if length(x)~=length(n)
y = NaN;
e = 1;
return
end
for i=1:length(x)
for j=1:n(i)
y(i) = y(i)*x(i);
end
end
e = 0;
return
end
Basic issue:
How do we get data from other sources into
Matlab so that we can play with it?
Other Issues:
Where do we get the data?
What types of data can we import
Easily or Not
load
Command opens and imports data from a
standard ASCII file into a matlab variable
Restrictions
Data must be constantly sized
Data must be ASCII
No other characters
load
Consider the simple file below
Create in notepad and save as test1.txt and
text2.txt
In matlab, set the path to the correct place (ie.
where the file is) and type load(test1.txt)
Now, type x = load(test1.txt)
12
test1
34
52
48
16 32
load
Now the file is no longer simple because not
every row has the same amount of characters
Create in notepad and save as test2.txt and
text2.txt
type y = load(test2.txt)
load
Now type in the same thing from test1.txt into
Excel and save the workbook as test1.xls
type y = load(test1.xls)
What happens?
Error!
test2
12
34
5
48
16 32
test1
12
34
52
48
16 32
load
Works for simple and unstructured code
Powerful and easy to use but limited
Will likely force you to manually handle
simplifying data which is prone to error
More complex functions are more flexible
fopen
Opens a file object in matlab that points to the
file of interest
fid = fopen(filepath)
absolute directory + filename
If file of interest is C:\Andrew\Project_1\file.dat
fid = fopen(C:\Andrew\Project_1\file.dat)
File Handling
f* functions are associated with file opening,
reading, manipulating, writing,
Basic Functions of Interest for opening and
reading generic files in matlab
fopen
fclose
fseek/ftell/frewind
fscanf
fgetl
fclose
When you are done with a file, it is a good idea
to close it especially if you are opening many
files
fclose(fid)
What is a File?
A specific organization of data
In matlab it is identified with a fid
Location is specified with a pointer that can be
moved around
fid
Pointer
file_name
Getting Data
Why move the pointer around?
Get somewhere in the file from where you want data
[data] = fscanf(fid,format,size)
Format
You have to tell matlab the type of data it should be
expecting in the text file so that it can convert it
%d, %f, %c, %s
Size
You can specify how to organize the imported data
[m,n] import the data as m by n, n can be infinite
Be careful because matlab will mangle your data and not tell
you
Lets Try It
Open text1.txt using the fopen command
Remember to save the fid, we will need it
Now use the size option to import the data with 5 rows and 2
columns
Try the same thing with test2.txt
It works and fills in the blanks. This is powerful but dangerous
Lets Try It
Open text1.txt using the fopen command
Remember to save the fid, we will need it
fid = fopen('test1.txt)
Create a variable with the data of text1.txt
[x] = fscanf(fid,'%f%f')
Now create another variable y with the data of text1.txt in it by using
fscanf (do not simply copy x)
[y] = fscanf(fid,'%f%f')
What happens here?
Need to set file pointer to beginning using frewind(fid)
Getting Data
fgetl returns the next line of the file as a
character array
You may need to convert these to numbers
>> fid1 = fopen(test1.txt);
>> a_str = fgetl(fid1)
a_str = 1 2
>> a_num = str2num(a_str)
a_num = [1 2]
Lets Try It
Now use the size option to import the data with 5 rows and 2
columns
[data2] = fscanf(fid,'%f%f',[5,2])
- Careful this is the same format as the original data but not the same
organization!!
frewind(fid)
[data3] = fscanf(fid,'%f%f',[2,5])
data3
- now the data is formatted correctly
Try the same thing with test2.txt
It works and fills in the blanks. This is powerful but dangerous
Realistic File
A realistic file of data will have header information,
labeled columns and other information embedded within
it.
Option 1: Manually go through deleting this information
and import using load of fopen commands.
Option 2: Have matlab delete and format available data
on the fly
Realistic File
Realistic File
Usage:
[var1 varN] =
textread(filename,format,args)
Summary
Lots of options to load files
load for basics
fscanf for complex
textread for most things
xlsread for Excel worksheets
Also saving Excel sheets as tab delimitted
Basics
Matlab has a powerful plotting engine that can
generate a wide variety of plots.
Generating Data
Matlab does not understand functions, it can
only use arrays of numbers.
a=t2
b=sin(2*pi*t)
c=e-10*t note: matlab command is exp()
d=cos(4*pi*t)
e=2t3-4t2+t
Line/Scatter
Simplest plot function is plot()
Try typing plot(y)
Matlab automatically generates a figure and draws the data and
connects its lines
Looks right, but the x axis units are incorrect
Line/Scatter
Plot a and then plot b
What do you see?
Only b
Matlab will replace the current plot with any new one
unless you specifically tell it not to
To have both plots on one figure use the hold on
command
To make multiple plots use the figure command
plot(t,a)
plot(t,b)
plot(t,a);
plot(t,a);
hold on;
figure;
plot(t,b);
plot(t,b);
Linespec
plot(a);
Hold on;
plot(b);
plot(c);
Hold off;
plot(d);
plot(a);
Hold on;
plot(b);
plot(c);
Hold off;
Figure;
plot(d);
plot(a);
Hold on;
plot(b);
plot(c);
Figure;
plot(d);
Linespec
Now we have added color, line style and markers to the data
We can also modify line width, marker edge and fill color and marker
size
Quick Assignment 1
Quick Assignment 1
Mini Assignment #1
4
t2
sin(2*pi*t)
3.5
figure
plot(t,a,'k','LineWidth',3); hold on;
plot(t,b,'ro')
xlabel('Time (ms)');
ylabel('f(t)');
legend('t^2','sin(2*pi*t)');
title('Mini Assignment #1')
3
2.5
f(t)
2
1.5
1
Mini Assignment #1
4
0.5
t2
sin(2*pi*t)
3.5
3
-0.5
2.5
-1
f(t)
0.2
0.4
0.6
0.8
1
1.2
Time (ms)
1.4
1.6
1.8
1.5
1
0.5
0
-0.5
-1
0.2
0.4
0.6
0.8
1
1.2
Time (ms)
1.4
1.6
1.8
Axis commands
Error Bars
We can alter the displayed range and other parameters of the plot by
using the axis command
Axis([xmin xmax ymin ymax])
Axis equal;
Axis square;
t2 = 0:1:10;
f = t2+(rand(1,length(t2))-0.5);
err1 = 0.1*f;
err2_l = 0.1*f;
err2_u = 0.25*f;
errorbar(t2,f,err1);
figure;
errorbar(t2,f,err2_l, err2_u);
2
1.5
Figure;
Plot(t,a,r);
Axis([-2 2 -2 2]);
1
0.5
0
-0.5
12
10
6
12
4
10
0
-2
10
12
-1
4
-1.5
2
-2
-2
-1.5
-1
-0.5
0.5
1.5
2
0
-2
10
12
Subplots
Quick Assignment 2
3.5
figure;
subplot(2,2,1)
plot(t,a);
subplot(2,2,2)
plot(t,b);
subplot(2,2,3)
plot(t,c);
subplot(2,2,4)
plot(t,d);
0.5
2.5
2
1.5
1
-0.5
0.5
0
0.5
1.5
-1
0.5
1.5
0.8
0.5
0.6
0
0.4
-0.5
0.2
0.5
1.5
-1
0.5
1.5
Functions a and b
0.5
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
Functions c and d
1
0.5
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
10
0.5
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
0.7
0.8
0.9
Functions c and d
1
0.5
0
0.1
0.2
0.3
0.4
0.5
0.6
10
12
Quick Assignment 2
1
Functions a and b
1
figure
subplot(3,1,1)
plot(t,a,t,b,'r');
axis([0 1 0 1]);
title('Functions a and b')
subplot(3,1,2)
plot(t,c,t,d,'m');
axis([0 1 0 1]);
title('Functions c and d')
subplot(3,1,3)
errorbar(t2,f,err1);
title('function f with errorbars')
Bar Graphs
So far we have focused on line/scatter plots, the other most common
plot type is a bar graph
Matlab bar(x,y,width) command will generate a bar graph that is
related to the underlying functions where the width of each bar is
specified by width (default = 1);
Can be used with subplot and all the other features we have
discussed so far
5
4.5
t3 = 0:1:25;
f = sqrt(t3);
bar(t3,f);
4
3.5
3
2.5
2
1.5
12
1
0.5
0
-5
10
15
20
25
30
Histograms
Quick Assignment 3
Note you can use histc function if you want to define bin edges instead
Can be used with subplot and all the other features we have
discussed so far
hist(b,10);
Figure;
Hist(b,[-1 -0.75 0 0.25 0.5 0.75 1]);
40
45
35
40
35
30
30
25
25
t = 0:0.1:1
for(i=1:25)
x(i,:) = exp(-10.*t) + 0.5*(rand(1,length(t))-0.5);
end
20
20
15
15
10
10
5
0
-1
-0.8
-0.6
-0.4
-0.2
0.2
0.4
0.6
0.8
0
-1.5
-1
-0.5
0.5
1.5
Quick Assignment 3
Quick Assignment
3
t = 0:0.1:1
Plot each individual trial (25 lines) in thin dotted black lines,
Plot the mean of the trials with a thick, red, dashed line and error
lines surrounding each datapoint that correspond to the standard
deviation of each of the points
Plot #2:
A histogram that expresses the distribution of the signal at the
end of each trial (last sample)
Error Rate
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.2
0.2
0.4
0.6
0.8
1.2
Repeat
Occurances
tip: remember about how matlab interprets matricies for the plot
command.
1.2
0
-0.25
-0.2
-0.15
-0.1
-0.05
0
Deviation (mm)
0.05
0.1
0.15
0.2
for(i=1:25)
x(i,:) = exp(-10.*t) + 0.5*(rand(1,length(t))-0.5);
end
mean_x = mean(x);
std_x = std(x);
figure
subplot(2,1,1)
plot(t,x,'k'); hold on;
errorbar(t,mean_x,std_x,'--r','LineWidth', 3);
title('Repeats of a Given Task')
xlabel('Repeat');
ylabel('Error Rate');
0.25
subplot(2,1,2)
hist(x(:,11),10)
title('Distribution of Endpoint Position');
xlabel('Deviation (mm)')
ylabel('Occurances')
Quick Assignment 3
Recap
1.2
1
Error Rate
0.8
plot,bar,hist
0.6
0.4
0.2
0
-0.2
-0.4
-0.2
0.2
0.4
0.6
0.8
1.2
Repeat
Occurances
Xlabel,title,legend,
0
-0.25
-0.2
-0.15
-0.1
-0.05
0
Deviation (mm)
0.05
0.1
0.15
0.2
0.25
3D Plots
Matlab provides a wide range of 3D plot
options, we will talk about 3 different plot
types.
Mesh, Surf, Contour
Dataset
Try [x,y,z] = peaks(25)
Does this work?
Mesh
Connects a series of discrete data points
with a mesh
Surf
Very similar to mesh, with filled grid
Contour
Meshc,surfc
Plot3
Plot commands
Plots lines and points in space, just like plot but now for an
(x,y,z) triple
Plot3(x,y,z), each a vector of equal length
Use all the same specfiers to generate colors, line-types,
etc.
View
Colorbar
caxis
Allows you to set the range of colors in the plot.
Caxis([min max]) will choose the range of colors
from the current color map to assign to the plot.
Values outside this range will use the min/max
available
Research
http://www.ifs.tuwien.ac.at/~silvia/research-tips/
Colormap
Plenty of other controls to personalize the
plot
colormap colormap_name sets to new map
Colormap (sets the types of colors that appear in 3D
plot). These can be custom of one of several premade
bone Hsv, jet, autumn, vga, summer,
See help graph3D for more
Use colormapeditor function for graphical selection of
color map