Académique Documents
Professionnel Documents
Culture Documents
introduction
CourseIntroduction_4
Goals
CourseIntroduction_5
Goals
CourseIntroduction_6
www.mathworks.com
Statistics Application development
Optimization tools:
Signal processing Matlab compiler
Matlab Excel builder
Image processing Matlab Com builder
Curve fitting Data acquisition and access
Bioinformatics toolbox tools
Financial toolbox Excel link
.... Data acquisition toolbox....
Database toolbox
CourseIntroduction_7
CourseIntroduction_9
CourseIntroduction_10
History
LINPACK, EISPACK.
(1970¶V
± In the mid-1970s, Cleve
Moler and several colleagues
developed the FORTRAN
subroutine libraries called
LINPACK and EISPACK
under a grant from the
National Science Foundation.
± LINPACK was a collection of
FORTRAN subroutines for
solving linear equations,
while EISPACK contained Jack Dongarra, Cleve Moler, Pete Stewart, and Jim Bunch in 1978
subroutines for solving
eigenvalue problems. C.... factor the A matrix
CALL SGEFA(A, N, N, IPVT, INFO)
± Together, LINPACK and
EISPACK represented state C.... copy B vector into X vector
of the art software for matrix CALL SCOPY(N, B, 1, X, 1)
computation. C.... solve the system of equations
CALL SGESL(A, N, N, IPVT, X, 0)
CourseIntroduction_11
History
Matlab 0 (1978)
± Cleve Moler designed (as a
"hobby" on his own time ) it to
give his students interactive
access to LINPACK and
EISPACK without having to learn
FORTRAN
± Moler named his program
Matlab, for MATrix LABoratory.
± Over the next several years,
when he would visit another
university to give a talk, or as a
visiting professor, he would end
up by leaving a copy of his
Matlab on the university
machines.
± Within a year or two, Matlab
started to catch on by word of
mouth within the applied math
community as a "cult"
phenomena CourseIntroduction_12
History
Matlab 1. (1984)
± reprogrammed in C
± commercial potential
=> Mathworks
± 1983, John Little was exposed to
Matlab because of a visit Cleve
made to Stanford.
± Little, an engineer, recognized
the potential application of
Matlab to engineering
applications.
± Little teamed up with Cleve
Moler and Steve Bangert to
develop a second generation,
professional version of Matlab
written in C and integrated with
graphics.
± The MathWorks, Inc. was
founded in 1984 to market and
continue development of Matlab.
CourseIntroduction_13
History
CourseIntroduction_15
Matlab: contra
CourseIntroduction_17
CourseIntroduction_18
CourseIntroduction_19
Scilab (www.scilab.org) is a
scientific software package for
numerical computations
providing a powerful open
computing environment for
engineering and scientific
applications
dictionary:
http://www.scilab.org/product/dic-mat-sci/SCI2M.htm
CourseIntroduction_20
References
Engineering
Computation with
MATLAB
David Smith
Pearson 2008
Mastering Matlab 7
Duane Hanselman
& Bruce Littlefield
Prentice Hall, 2004
CourseIntroduction_21
References
CourseIntroduction_23
MATLAB
desktop
Introduction to Matlab
Desktop_2
Current Directory
Location of the folder that contains scripts that
you have written and any data files you want to
analyze
Workspace/Array editor
Lists variables from
code and experiments
you have run
double-click the
variable opens a
window showing the
values
values can be changed
interactively
Desktop_9
Command Window
main working area
can run lines of code
displays values if code
is not concluded with ;
pushing up arrow
cycles through previous
entries
Desktop_10
Command History
displays a log of the
statements most
recently run in the
Command Window
user can copy from this
list one or more lines of
code and paste it into
the command window
saves history (up to
20k)
Desktop_11
Desktop layout
Layout can be changed
Different windows can be shown (or not)
Windows can be docked/undocked
HELP
Click on Help-icoon
helpdesk
help + command name: online help in Command
Window
helpwin + command name: online help in Help
Window
doc + command name: online documentation
lookfor + search string: search for search string in
Matlab path
Desktop_12
HELP
Desktop_13
HELP
>> help
HELP topics
Editing keys
Key Function
Browse backward through the
commands
Browse forward through the
commands
Scroll backward through a
single command
Scroll forward through a
single command
ctrl Scroll backward through a
single command by word
ctrl Scroll forward through a
single command by word
home Jump to the beginning of the
command line
end Jump to the end of the
command line
esc Clear line
del Discard character under cursor
backspace Discard character in front of
the cursor
tab Complete a command (select
from the list)
Desktop_18
Variables and Names
Desktop_19
Reserved Words
Matlab has some special (reserved) words that you may
QRWUHXVH«
Use the iskeyword to list all reserved words.
for switch
end continue
if else
while try
function catch
return global
elsif persistent
case break
Desktop_20
otherwise
Case Sensitivity
Desktop_21
Matlab as a calculator
Desktop_22
Built-in functions
Desktop_24
Elementary math functions
Exponential. Complex.
exp - Exponential. abs - Absolute value.
expm1 - Compute exp(x)-1 accurately. angle - Phase angle.
complex - Construct complex data from real
log - Natural logarithm. and imaginary parts.
log1p - Compute log(1+x) accurately. conj - Complex conjugate.
log10 - Common (base 10) logarithm. imag - Complex imaginary part.
log2 - Base 2 logarithm and dissect real - Complex real part.
floating point number. unwrap - Unwrap phase angle.
pow2 - Base 2 power and scale isreal - True for real array.
floating point number. cplxpair - Sort numbers into complex conjugate
pairs.
realpow - Power that will error out on
complex
Rounding and remainder.
result.
fix - Round towards zero.
reallog - Natural logarithm of real floor - Round towards minus infinity.
number. ceil - Round towards plus infinity.
realsqrt - Square root of number greater round - Round towards nearest integer.
than or equal to zero. mod - Modulus (signed remainder after
sqrt - Square root. division).
nthroot - Real n-th root of real numbers. rem - Remainder after division.
nextpow2 - Next higher power of 2. sign - Signum.
Desktop_25
Desktop_26
Some Special Variables
Desktop_27
Format
Desktop_28
Matlab Programs
&DQZHH[HFXWHD³SURJUDP"´RULVLWDVLPSOHFDOFXODWRU"
Programs in Matlab are:
± Scripts: Matlab statements that are fed from a file into the
Command Window and executed immediately
± Functions: Program modules that are passed data (arguments)
and return a result (i.e., sin(x))
± These can be created in any text editor (but Matlab supplies a nice
built-in editor)
Desktop_29
Editor
Access to
commands
Color keyed
text with auto
indents
Desktop_30
Summary
desktop environment
try to use help as much as possible
besides Matlab Help there is also google
use Matlab interactively as a calculator
Desktop_31
MATLAB
numeric data types
Basic Data Structure
array:
± most basic data structure in Matlab
± a two-dimensional, rectangularly shaped data
structure
± can contain numbers, characters, logical states
Matlab uses these two-dimensional arrays to
store single numbers and linear series of
numbers as well. In these cases, the
dimensions are 1-by-1 and 1-by-n respectively,
where n is the length of the numeric series.
Matlab also supports data structures that have
more than two dimensions.
data types
user function
cell structure
classes handles
overview
Numeric Data Types
integer
4 signed and 4 unsigned integer data types.
Signed types:
± enable negative integers as well as positive,
± represent smaller range of numbers as the unsigned types
Unsigned types
± wider range of numbers
± zero or positive.
Matlab supports 1-, 2-, 4-, and 8-byte storage for integer
data.
± save memory and execution time for your programs if you use
the smallest integer type that accommodates your data.
± no need for a 32-bit integer to store the value 100.
integer
integer
ArraysCreation_2
Topics
Creating
± how to build an array in a fast way
± manual entering the elements
± :
± linspace, logspace
± special functions, special matrices
Indexing
± How to select elements
Help
Search for
Creating and Concatenating Matrices
Matrices and Arrays
Matrix Indexing
Elementary matrices
ArraysCreation_4
Matlab Arrays
Vectors: magnitude
r ANDr direction
force 12.74 i 5.234 j
r r r r r r
H a1i1 a2i2 a3i3 a4i4 L anin
Creating Arrays
Different ways:
± specify each element explicitly,
± use the colon : operator,
± use the commands linspace or
logspace
± elementary (built-in) arrays
The Matlab arrays are indexed as:
A(row,column)
ArraysCreation_6
Creating Arrays
11 2 3
» c = [1;2;3]
c =
1
2
3
ArraysCreation_7
Creating Arrays
Example
» D = 1:4 » d(:)
D = ans =
1 2 3 4 1
» E = 1:0.3:2 11
E = 1
1.0000 1.3000 2
1.6000 1.9000 2
» d 2
d = 3
1 2 3 3
11 2 3 3
1 2 3 » d(2:3)
» d(2,:) ans =
ans = 11 1
11 2 3 » d(8:9)
» d(:,1) ans =
ans = 3 3
1 » d(end:-1:6)
11 ans =
ArraysCreation_10
1 3 3 3 2
Creating Arrays
linspace
± syntax: x = linspace(first, last, n)
± creates linearly spaced row vector starting with first, ending at
last , having n elements
logspace
± syntax: x = linspace(first, last, n)
± creates logarithmically spaced row vector starting with 10first,
ending at 10last , having n elements
ArraysCreation_11
Creating Arrays
Elementary matrices.
zeros - Zeros array.
ones - Ones array.
eye - Identity matrix.
repmat - Replicate and tile array.
rand - Uniformly distributed random numbers.
randn - Normally distributed random numbers.
linspace - Linearly spaced vector.
logspace - Logarithmically spaced vector.
freqspace - Frequency spacing for frequency response.
meshgrid - X and Y arrays for 3-D plots.
accumarray - Construct an array with accumulation.
: - Regularly spaced vector and index into matrix .
ArraysCreation_12
Examples
>> ones(3) >> randn(3,2)
ans =
ans = -0.4326 0.2877
-1.6656 -1.1465
1 1 1 0.1253 1.1909
1 1 1 >> a=1:4
1 1 1 a =
>> zeros(2,5) 1 2 3 4
>> diag(a)
ans = ans =
0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 2 0 0
0 0 3 0
>> eye(3) 0 0 0 4
Size of a Matrix
numel() command.
>> n = numel(A)
n =
9
length() command (vector)
± the statement length(X) is equivalent to max(size(X))
>> length(A)
ans =
Transposing a Matrix
Repeating Arrays
reshape
syntax: B = reshape(A,m,n)
returns the m-by-n matrix B whose elements are taken
columnwise from A. An error results if A does not have
m*n elements.
repmat
syntax B = repmat(A,m,n)
creates a large matrix B consisting of an m-by-n tiling of
copies of A.
repmat(A,n) creates an n-by-n tiling.
ArraysCreation_18
Reshaping
reshape >> x = 1:9
B = reshape(A,m,n)
returns the m-by-n matrix B
whose elements are taken x =
columnwise from A. An error
results if A does not have m*n 1 2 3 4
elements. 5 6 7 8
9
>> reshape(x,3,3)
ans =
1 4 7
2 5 8
3 6 9
More functions
Function Description
[a,b] or Create a matrix from specified elements, or concatenate matrices together.
[a;b]
accumarray Construct a matrix using accumulation.
blkdiag Construct a block diagonal matrix.
cat Concatenate matrices along the specified dimension.
diag Create a diagonal matrix from a vector.
horzcat Concatenate matrices horizontally.
magic Create a square matrix with rows, columns, and diagonals that add up to the same
number.
ones Create a matrix of all ones.
rand Create a matrix of uniformly distributed random numbers.
repmat Create a new matrix by replicating or tiling another.
vertcat Concatenate two or more matrices vertically.
zeros Create a matrix of all zeros.
ArraysCreation_20
Concatenate
cat
Concatenate arrays
Syntax
± C = cat(dim,A,B)
± C = cat(dim,A1,A2,A3,A4...)
C = cat(dim,A,B) concatenates the arrays
A and B along dim.
C = cat(dim,A1,A2,A3,A4,...)
concatenates all the input arrays (A1, A2, A3,
A4, and so on) along dim.
cat(2,A,B) is the same as [A,B]
cat(1,A,B) is the same as [A;B]
Indexing
Assignment of elements
Deletion
Summary
ex.: demo_array_creation
ArraysCreation_28
MATLAB
array operations
Topics
Mathematical operations
Manipulation
Sorting and searching
More built-in manipulation
Multidimensional arrays
ArraysOperations_2
Help
Search for
Arithmetic operators
Array operators
ArraysOperations_4
Dot (Array) Operations
ArraysOperations_5
Scalar-Array Mathematics
Addition, >> g = [1 2 3 4; 5 6 7 8]
subtraction, g =
1 2 3 4
multiplication, and 5 6 7 8
array. ans =
1 3 5 7
9 11 13 15
>> 3*g/5+4
ans =
ArraysOperations_6
Array-Array Mathematics
ArraysOperations_7
Array-Array Mathematics
ArraysOperations_8
Example
>> g >> g + h
g = ans =
1 2 3 4 2 3 4 5
5 6 7 8 7 8 9 10
9 10 11 12 12 13 14 15
h = ans =
1 1 1 1 1 3 5 7
2 2 2 2 8 10 12 14
3 3 3 3 15 17 19 21
>>
ArraysOperations_9
Example
>> g*h » g * h'
??? Error using ==> mtimes
Inner matrix dimensions ans =
must agree.
10 20 30
26 52 78
>> g.*h 42 84 126
» g' * h
ans =
ans =
1 2 3 4
10 12 14 16 38 38 38 38
27 30 33 36 44 44 44 44
50 50 50 50
56 56 56 56
ArraysOperations_10
More on Array Operations
Most Matlab functions will >> A=[1 2 3 4 5];
work equally well with >> sin(A)
ans =
both scalars and arrays
0.8415 0.9093
(of any dimension) 0.1411 -0.7568
-0.9589
>> sqrt(A)
ans =
1.0000 1.4142
1.7321 2.0000
2.2361
ArraysOperations_11
>> mean(A)
ans =
4 5 6
>> sum(A)
ans =
12 15 18
ArraysOperations_12
Reversing
reversing rows and >> a = [1 2 3 ; 4 5 6 ; 7 8 9]
columns a =
1 2 3
4 5 6
7 8 9
>> b = a(end:-1:1)
b =
9 6 3 8 5
2 7 4 1
>> b = a(end:-1:1,1:3)
b =
7 8 9
4 5 6
ArraysOperations_13 1 2 3
Sorting
Sort array elements in >> a = randperm(8)
ascending or descending a =
8 2 7 4 3 6
order 5 1
Syntax >> b = sort(a)
b =
± B = sort(A) 1 2 3 4 5 6
7 8
± B = sort(A,dim) >> A
± B = sort(...,mode) A =
± [B,IX] = sort(...) 3 7 5
0 4 2
B = sort(A) sorts the >> sort(A)
elements along different ans =
0 4 2
dimensions of an array, and 3 7 5
arranges those elements in >> sort(A,1)
ans =
ascending order.
If A is a ...sort(A) ... 0 4 2
3 7 5
± Vector: Sorts the elements of >> sort(A,2)
A. ans =
± Matrix: Sorts each column of 3 5 7
0 2 4
A.
ArraysOperations_14
Sorting
a =
B = sort(A,dim) sorts
the elements along the 6
7
4
8
1
2
5
3
dimension of A specified
by a scalar dim. If dim is >> [xs indx] = sort(a,
a vector, sort works 'descend')
iteratively on the
specified dimensions. xs =
Thus, sort(A,[1 2]) is
equivalent to 8 7 6 5
sort(sort(A,2),1). 4 3 2 1
B = sort(...,mode)
sorts the elements in the indx =
specified direction,
depending on the value 2 1 5 8
of mode. 6 4 3 7
±
DVFHQGµ Ascending order
(default)
ArraysOperations_15
±
GHVFHQGµDescending order
Searching
The find FRPPDQG³ILQGV´ >> grades = -5: 10: 105
grades =
members of an array that -5 5 15 25 35
meet a criteria. The 45 55 65 75 85
result of the command is 95 105
>> set1 = find(grades>100 |
a list of element numbers. grades <0)
set1 =
1 12
>> set2 = find(grades>=0 &
grades <=100)
set2 =
2 3 4 5 6
7 8 9 10 11
>> grades(set1)
ans =
-5 105
>> grades(set2)
ans =
5 15 25 35 45
55 65 75 85 95
ArraysOperations_16
Searching
The find FRPPDQG³ILQGV´ >> a = 1:9
works also in 2 dimensions a =
1 2 3 4 5 6
more specific 7 8 9
>> a = reshape(a,3,3)'
find(X, n): a =
1 2 3
start at the first element 4
7
5
8
6
9
returns up to n indices where >> [ii,ij]=find(a>5)
X is true ii =
3
ILQG;Q¶ODVW¶ 3
2
start at the last element 3
returns up to n indices where ij =
1
X is true 2
3
3
>> k = find(a>5)
k =
3
6
8
9
>> l = find(a>5, 2, 'last')
l =
ArraysOperations_17 8
9
Built-in functions
help elmat: Matrix manipulation. a =
1 2 3
fliplr: Flip matrix in left/right 4 5 6
7 8 9
direction. >> flipud(a)
flipud: Flip matrix in up/down ans =
7 8 9
direction. 4 5 6
rot90: Rotate matrix 90 degrees. 1 2 3
>> fliplr(a)
rot90(a,n): Rotate n-times ans =
circshift(A,shiftsize) 3 2 1
6 5 4
circularly shifts the values in the array, 9 8 7
A, by shiftsize elements. >> rot90(a)
± shiftsize is a vector of integer scalars ans =
3 6 9
where the n-th element specifies the 2 5 8
shift amount for the n-th dimension of 1 4 7
array A. >> rot90(a,2)
ans =
± positive shiftsize: shift down (or to the 9 8 7
right). 6 5 4
± negative shiftsize: shift up (or to the 3 2 1
>> circshift(a,[-1 1])
left). ans =
± 0: no shift 6 4 5
9 7 8
ArraysOperations_18 3 1 2
Built-in functions
diag - Diagonal a =
1 2 3
matrices and diagonals of 4 5 6
7 8 9
matrix. >> diag(a)
ArraysOperations_19
Multidimensional Arrays
ArraysOperations_21
ArraysOperations_22
Functions & Arrays
ArraysOperations_23
ArraysOperations_24
Functions on matrix
ArraysOperations_25
MATLAB
relational and logical
operators
Topics
LogicalRelational_2
Help
Search for
Logical operator
Relational operator
Logical Expressions
Why?
What if you want to choose between two (or more)
possible programming paths?
Use a logical condition to decide what to do next
Requires logical operators
LogicalRelational_4
LogicalRelational_5
Relational Operators
Used to compare two
Relational Operators:
numeric values < less than
Returns a value of true <= less than or equal to
or false. > greater than
In Matlab, >= greater than or equal to
== equals to
± 1 = true (any non-zero
number); ~ = not equal to
± 0 = false;
± Logical data type
LogicalRelational_6
Operator Precedence
1. Parentheses ()
2. Transpose (.'), power (.^), complex conjugate transpose ('), matrix
power (^)
3. Unary plus (+), unary minus (-), logical negation (~)
4. Multiplication (.*), right division (./), left division (.\), matrix
multiplication (*), matrix right division (/), matrix left division (\)
5. Addition (+), subtraction (-)
6. Colon operator (:)
7. Less than (<), less than or equal to (<=), greater than (>), greater
than or equal to (>=), equal to (==), not equal to (~=)
8. Element-wise AND (&)
9. Element-wise OR (|)
10. Short-circuit AND (&&)
11. Short-circuit OR (||)
Operator Precedence
LogicalRelational_8
LogicalRelational_10
Logical Operators
Logical Operators:
± Provide a way to combine results
from Relational Expressions or Logical Operators
between logical values
± Returns a value of true or false. & AND
Evaluated after all other | OR
operators have been
performed. ~ NOT
xor XOR
LogicalRelational_11
Logical Operators
AND: &
± Returns true if two expressions being compared are true.
± Returns false if any of the two is false.
OR: |
± Returns true if any of the two expressions is true.
± Returns false only if the two are both false.
NOT: ~
± Returns true if the single expression is false.
± Returns false if the single expression is true.
LogicalRelational_12
Examples:
Assume: a=7; b=4; c=3;
~(a==3*b)
± Evaluates: 3*b = 12
± Evaluates: (a==12) and result is false
± Evaluates ~(false) and result is true
± Returns ans = 1 (true)
a > 5 & b > 5
± Evaluates (a>5) and (b>5) separately.
± One returns true, the other returns false.
± Since both are not true, the expression returns false.
a == 7 | b ==1
± Evaluates (a==7) and (b==1) separately
± One returns true and the other returns false
± Since at least one is true, the expression returns true
Logical Operators: more
LogicalRelational_14
LogicalRelational_15
Logical Operators: more
Bit-Wise Functions
bit-wise logical operations on nonnegative integer
inputs.
inputs may be scalar or in arrays.
examples
A = 28;
% binary 11100
B = 21;
% binary 10101
LogicalRelational_16
Short-Circuit Operators
The following operators perform AND and OR
operations on logical expressions containing scalar
values.
They are short-circuit operators in that they evaluate
their second operand only when the result is not fully
determined by the first operand.
LogicalRelational_17
Example
example: logical_ex_1.m
x=5;
y=10;
disp(x <y)
disp(x<=y)
disp(x==y)
disp((x>10) & (y<30))
disp((x>2) | (y > 89))
LogicalRelational_18
A Common Mistake
You will not get into trouble if you make sure that Logical
Operators are always used with logical values.
A > B & C (where A=10, B=5, C=0)
± This looks like a relational expression asking if A is greater than
both B and C which should be true for these values.
± Here is what really happens:
A>B is evaluated as true
result (true) is logically ANDed with C
Since Matlab treats any zero numeric as false, it will mistakenly treat C
as a logical and the result will be false
± The CORRECT form is: (A > B) & (A > C)and this returns a
true result.
± NOTE: subtle problems can arise because Matlab uses numerics to
represent logical values. Other languages are stricter in this area
DQGZRQ¶WOHWWKLVKDSSHQ
Logical Values in Assignments
True/False values can be assigned to variables
DQGWKHQWUHDWHGQXPHULFDOO\LQ0DWODE«
The variables will be assigned the value that is
returned from relational and/or logical operators.
The variables will thus have a value of 1 or 0.
Example: a=7; b=4; c=3;
± x = a > 2;
Then x = 1;
± y = b==5;
Y will be equal to 0.
This can be very useful in Matlab but it is actually
quite DANGEROUS
More Examples
LogicalRelational_21
Practice
± a = 4; b = 20; c = 12; d = 5;
± One = a>4 & b==20
± Two = b<40 | c>10
± Three = d.*c > a.*b
± Four = b.*3<= 100 & d<10 & a.*d==b
LogicalRelational_22
More Practice
a = [0,2,4,2]; b = [4,1,-2,3];
What is:
C = a .* b;
C = b.^2-a.*b
C = a >= b;
>> B=[2:-1:-2]
B = 2 1 0 -1 -2
>> numerator=ones(size(B))
numerator = 1 1 1 1 1
>> numerator./B
Warning: Divide by zero.
ans = 5.0000e-001 1.0000e+000 Inf -1.0000e+000 -5.0000e-001
>> B=B+(B==0)*eps
B = 2.0000e+000 1.0000e+000 2.2204e-016 -1.0000e+000 -2.0000e+000
>> numerator./B
LogicalRelational_24
ans = 5.0000e-001 1.0000e+000 4.5036e+015 -1.0000e+000 -5.0000e-001
6RPH2WKHU:DUQLQJV«
Using numeric values to represent logicals can have some
VWUDQJHUHSHUFXVVLRQV«
Never try to use NaN in a relational or logical expression
because NaN has no value and therefore could be
considered to have all values!
aa = [ 10 16 16 16 17 9 11]
>> aa > 15
>> nan==nan
ans = 0 1 1 1 1 0 0 ans =
>> aaa = ans
>> aa(aaa) 0
ans =
16 16 16 17 >> inf==inf
>> aaai = uint16(aaa)
aaai = ans =
0 1 1 1 1 0 0
>> aa(aaai)
1
??? Subscript indices must either be real positive
integers or logicals.
Logical Functions
Matlab includes a large number of logical functions
(functions that return a true or false result)
0DQ\RIWKHPRVWXVHIXODUHZKDWDUHFDOOHG³LVD«´
functions
see also functions:
± any( )
± all( )
± find( )
LogicalRelational_26
1 0
anySeniors = noSeniors =
0 1
LogicalRelational_27
Summary
Matlab can store and Relational Operators:
manipulate much more < less than
than simply numbers <= less than or equal to
logical expressions on > greater than
arrays >= greater than or equal
to
GRQ¶WIRUJHW == equals to
~ = not equal to
Logical Operators
& AND
| OR
~ NOT
xor XOR
MATLAB
interactive plotting
Topics
GraphicsInteractive_2
GraphicsInteractive_3
GraphicsInteractive_4
GraphicsInteractive_6
Plotting Tools
Start:
± use the plottools
command.
± from the figure toolbar -
Show Plot Tools icon .
3 basic plotting tools
± Figure Palette,
± Plot Browser,
± Property Editor.
basic plotting tools
GraphicsInteractive_7
GraphicsInteractive_8
GraphicsInteractive_10
GraphicsInteractive_12
Plot Browser
provides a legend of all the graphs in the figure. It
lists each axes and the objects (lines, surfaces,
etc.) used to create the graph.
Plot Browser
GraphicsInteractive_13
Property Editor
HQDEOHV\RXWRDFFHVVDVXEVHWRIWKHVHOHFWHGREMHFW¶V
properties.
when no object is selected, the Property Editor displays
WKHILJXUH¶VSURSHUWLHV
Ways to Display the Property Editor
± Double-click an object when plot edit mode is enabled.
± Select an object and right-click to display its context menu, then
select Properties.
± Select Property Editor from the View menu.
GraphicsInteractive_14
Property Editor
Property Editor
enables you to
change the
most
commonly
used object
select an
object, the
property editor
changes
accordingly
to access all
object
properties, use
the Property
Inspector.
GraphicsInteractive_15
GraphicsInteractive_16
Saving Your Work
GraphicsInteractive_17
GraphicsInteractive_18
Generate code
generate code to reproduce this graph by
selecting Generate M-File from the Figure
menu.
Matlab creates a function that recreates the
graph and opens the generated M-File in the
editor.
This feature is particularly useful for capturing
property settings and other modifications made
using the plot tools GUI.
Data Arguments
Generated functions do not store the data
necessary to recreate the graph.
You must supply the data arguments
Limitations
Attempting to generate code for graphs
containing a large number of graphics objects
(e.g., greater than 20 plotted lines) might be
impractical.
MATLAB
basic mathematical
applictions
Topics
basicMath_2
Import Wizard for data import
± File-!,PSRUW'DWD«
File input with load
± B = ORDGµGDWDLQW[W¶
File output with save
± VDYHµdataout¶µ$¶µ-ascii¶
help datafun
Search for:
± Data analysis
Minimum of in a Data Set >> min(v)
Maximum of in a Data Set >> max(v)
Sum of a Data Set >> sum(v)
Standard Deviation >> std(v)
Mean of a Data Set >> mean(v)
Sort a Data Set in ascending order>> sort(v)
remark:
MATLAB considers databasicMath_4
sets stored in column-oriented
arrays
mean
>> temp3city =
>> mean(temp3city, 1)
12 8 18 ans = vectors: mean(X) is the
15
12
9
5
22
19
11.9677 8.2258
>> mean(temp3city, 2)
19.8710
mean value of the
14
12
8
6
23
22
ans = elements in X.
12.6667
11
15
9
9
19
15 15.3333 matrices, mean(X) is a
8
19
10
7
20
18
12.0000
15.0000
row vector containing the
12
14
7
10
18
19
13.3333
13.0000
mean value of each
11
9
8
7
17
23 13.0000 column.
8
15
8
8
19
18
12.6667
14.6667 mean(X,DIM) takes the
8
10
9
7
20
17
12.3333
14.3333
mean along the
12
9
7
8
22
19 12.0000 dimension DIM of X.
12 8 21 13.0000
12 8 20 11.6667
10 9 17 13.6667
13 12 18
12.3333
9 10 20
10 6 22 11.3333
14 7 21 13.6667
12 5 22 12.0000
13 7 18 13.6667
15 10 23
13.3333
13 11 24
12 12 22 12.0000
14.3333
13.0000 basicMath_5
«
median
median(x) same as >> X = [0 1 2; 3 4 5]
mean(x), only returns X =
the median value.
0 1 2
3 4 5
>> median(X,1)
ans =
>> median(X,2)
ans =
1
4
basicMath_6
std
Standard deviation >> dat =
>> std(dat)
There are two common textbook 12 8 18 ans =
definitions for the standard deviation s of 15 9 22 2.5098 1.7646
a data vector X. 12 5 19 2.2322
14 8 23 >> std(dat,1)
Def_1 12 6 22 ans =
1 11 9 19
n 2.4690 1.7360
1 2 2
s xi x 15 9 15
2.1959
n 1i 1 8 10 20
>> std(dat,0,2)
19 7 18
12 7 18 ans =
Def_2 14 10 19 5.0332
1 11 8 17 6.5064
n
1 2 2 9 7 23
s xi x 7.0000
n i 1
8 8 19
7.5498
15 8 18
s = std(X) 8 9 20 8.0829
X is a vector, returns the standard 10
12
7
7
17
22
5.2915
deviation using (1) above. X is a matrix, 9 8 19
3.4641
std(X) returns a row vector containing the 12 8 21
6.4291
standard deviation of the elements of 12 8 20 6.6583
10 9 17 5.5076
each column of X. 13 12 18 4.5092
s = std(X,flag) 9 10 20 4.5826
flag = 0, is the same as std(X). 10
14
6
7
22
21
8.7178
flag = 1, std(X,1) returns the standard 12 5 22 6.3509
deviation using (2) 13 7 18 5.1316
s = std(X,flag,dim) computes the 15
13
10
11
23
24
6.6583
standard deviations along the dimension 12 12 22
5.1316
7.6376
of X specified by scalar dim. Set flag to 0
4.3589
to normalize Y by n-1; set flag to 1 to ...
basicMath_7
normalize by n
max (min)
>> dat = >> max(dat)
max Largest component. 12 8 18
ans =
15 9 22
vectors: MAX(X) is the 12
14
5
8
19
23 19 12 24
largest element in X. 12
11
6
9
22
19
matrices: MAX(X) is a row 15
8
9
10
15
20
>> max(max(dat))
each column. 9
8
7
8
23
19 >> max(dat(:))
max(X,[],DIM) operates
along the dimension DIM.
diff
>> dat = >> Y
Y = diff(X) calculates Y =
19 12 24
12 8 18
differences between adjacent 15 9 22
>> diff(Y)
ans =
elements of X. 12
14
5
8
19
23
-7 12
>> diff(Y,2)
vector: returns a vector, 1 12
11
6
9
22
19
ans =
19
element shorter than X, of 15 9 15 >> diff(dat)
ans =
differences between adjacent 8
19
10
7
20
18
3 1 4
filter
time_series =
12 17 10 22 15 11 18
27 14
a =
>> filter(a,1,time_series)
ans =
Columns 1 through 8
Column 9
21.5000
basicMath_11
more functions
Tips:
Check Cleve 0ROHU¶V website
± www.mathworks.com/moler
Help
± Search in helpdesk data analysis
± Interpolation
± fitting
BasicDataAnalysis_13
Interpolation
(VWLPDWHDYDULDEOH¶VYDOXHEHWZHHQNQRZQYDOXHV
± When you take data, how do you predict what other
data points might be?
± Two techniques are :
Linear Interpolation
Extrapolation
Interpolation
±demo_interp1
±demo_interp2
±demo_interp3
BasicDataAnalysis_15
Fitting
basicMath_16
Linear regression
Polynomial Fit
built-in tool
basicMath_20
polynomials
Polynomials are described by using a row vector of the coefficients of the
polynomial beginning with the highest power of x and inserting zeros for
³PLVVLQJ´WHUPV
f=[9 ±5 3 7];
g=[6 ±1 2];
multiply and divide polynomials by using the conv and deconv functions
y=conv(f,g)
[q r]=deconv(y,f)
polynomials
2x1 3x2 8
5x1 4x2 13
A = [2 3; 5 4]
b = [8;13]
x = A\b
LinearEquations_23
Solution?
2 x1 3x2 4
4 x1 6 x2 7
A = [2 3; 4 6]
b = [4;7]
x = A\b
LinearEquations_24
Simultaneous Linear Equations
Basic form:
LinearEquations_25
Solution of equations
2x1 +4x2-2x3=4
4 x1+9x2-2x3=6
-2 x1-3x2+7x3=10
demo_lineq3
basicMath_26
The coefficient matrix A need not be square. If A is m*n,
there are three cases.
± m=n
Square system.
Seek an exact solution.
± m>n
Over determined system.
Find a least squares solution.
± m<n
Underdetermined system.
Find a basic solution with at most m nonzero components.
basicMath_27
Linear Equations
basicMath_28
backslash \
Steps in A\b
Stop if successful
If A is upper or lower triangular, solve by back/forward substitution
If A is permutation of triangular matrix, solve by permuted back
substitution (useful for [L,U]=lu(A) since L is permuted)
If A is symmetric/hermitian
± Check if all diagonal elements are positive
± Try Cholesky, if successful solve by back substitutions
If A is Hessenberg (upper triangular plus one subdiagonal), reduce
to upper triangular then solve by back substitution
If A is square, factorize PA = LU and solve by back substitutions
If A is not square, run Householder QR, solve least squares
problem
Basic optimization
basicMath_31
Zero finding
Minimization in 1 dimension
demo_fminbnd_3
Minimization in n dimensions