Upload
alfie-cocteau
View
213
Download
0
Embed Size (px)
Citation preview
7/28/2019 01_28864_Matlab_Syntax_E2011
1/24
1
28864. Introduction to Matlab programming
Krist V. Gernaey
Outline
Introduction
Matlab syntax: useful commands to get started
Working with vectors and matrices
Matlab scripts and functions
31 August 201128864
Matlab programming control
File input / output
7/28/2019 01_28864_Matlab_Syntax_E2011
2/24
2
Outline
Introduction
How to use the Matlab help function?
Matlab syntax: useful commands to get started
Working with vectors and matrices
Matlab scripts and functions
31 August 201128864
Matlab programming control
File input / output
What is Matlab?
The name Matlab stands for MATrix LABoratory
.instructional tool for introductory and advanced courses in mathematics,engineering, and science (e.g. course 28150).
Matlab: basic license (basic functionality) that can be extended with add-on application-specific solutions (toolboxes). Toolboxes are collections ofMatlab functions (M-files) that extend the Matlab environment to solveparticular classes of problems.
31 August 201128864
Detailed info: www.mathworks.com
7/28/2019 01_28864_Matlab_Syntax_E2011
3/24
3
Free Matlab alternatives
Octave (www.octave.org)
Very similar
Scilab (www.scilab.org)
Syntax differences
Windows supported
31 August 201128864
Starting and quitting Matlab
Starting Matlab:
By double-clicking the Matlab icon on the desktop of your Windows
By selecting Matlab from the program list
Quitting Matlab:
Click the Close box in the Matlab desktop.
Select Exit Matlab from the desktop File menu.
Press Ctrl + Q
Type qui t at the Command Window prompt.
31 August 201128864
7/28/2019 01_28864_Matlab_Syntax_E2011
4/24
4
The Matlab desktop (Matlab 6.5)
31 August 201128864
The Matlab desktop (Matlab 7.0)
31 August 201128864
7/28/2019 01_28864_Matlab_Syntax_E2011
5/24
5
Outline
Introduction
ow o use e a a e p unc on
Matlab syntax: useful commands to get started
Working with vectors and matrices
Matlab scripts and functions
31 August 201128864
Matlab programming control
File input / output
How to use the Matlab help function?
The traditional way of getting help:
>>hel p f unct i onname
Example: >>hel p sqr t
Use the Matlab Helpbrowser
>>hel pbrowser
>>hel pwi n f unct i onname
Use Matlab help from the Help menu
31 August 201128864
Using the Matlab Start button
Get Help from the toolbar
7/28/2019 01_28864_Matlab_Syntax_E2011
6/24
6
Help at www.mathworks.com
Go to Support (http://www.mathworks.com/support/)
Documentation
Information about Matlab based books
Etc.
31 August 201128864
Matlab books, introduction to Matlab
Essential Matlab for engineers andscientists (3rd Edition)
Brian Hahn and Dan Valentine (2007)
Elsevier, Paperback, 448 pages
ISBN-13: 978-0-7506-8417-0
31 August 201128864
7/28/2019 01_28864_Matlab_Syntax_E2011
7/24
7
Outline
Introduction
Matlab syntax: useful commands to get started
Working with vectors and matrices
Matlab scripts and functions
31 August 201128864
Matlab programming control
File input / output
Matlab commands to get started
>>demo % Launches the Matlab Helpbrowser to the Demos tab, containing
information on all demos available in Matlab
>>ver % Displays Matlab, Simulink, and toolbox version information
>>whos % Lists the variables that are currently defined in the Matlab
Workspace, long version with detailed information
>>who % Like whos, but will only list the names of the variables
31 August 201128864
>>what % Lists the Matlab specific files in the current directory, sorted by
file type
>>pwd % Lists the name of the current directory
7/28/2019 01_28864_Matlab_Syntax_E2011
8/24
8
Matlab commands to get started
>>cl ear % Clear all variables from the memory. As a result, the
Matlab Workspace will be empty
>>cl ear dat a % Clear the variable data from the memory.
>>cl c % Clear the Matlab Command Window
>>cl ose al l % Close all figure windows
These commands are useful at the start of a script, when you want to be
31 August 201128864
calculations!
Defining variables in Matlab
Variable names are case sensitive
Y1 and y1 are 2 different variables!!!
Variable names can contain up to 63 characters (as of Matlab 6.5 andnewer)
Use namel engt hmax to check
Variable names must start with a letter followed by letters, digits, andunderscores
OK: a5, x_27, substrate, S_NH, ...
31 August 201128864
, ...
If you are not sure whether a variable name is correct, use i svar name to
check
7/28/2019 01_28864_Matlab_Syntax_E2011
9/24
9
Defining variables in Matlab
Keywords are protected!!!
Use i skeyword to check
Matlab function names can be overwritten if you declare a variable with aname that is identical to the name of a function!
The function can be used again after clearing the variable with thefunction name
Some Matlab functions are often overwritten in programming, e.g. i ,j ,hel , s i ze,
31 August 201128864
Defining variables in Matlab
An illustrative example:
E.g.: >> hel p=5;
hel p =
5
>> cl ear hel p
>> hel p
31 August 201128864
HELP t opi cs
. . .
7/28/2019 01_28864_Matlab_Syntax_E2011
10/24
10
Special variables in Matlab
>>ans % Default variable name for results
>>pi % Value of
>>i nf % Infinity
>>NaN % Not a number, e.g. 0/0
>>i
>>j % i = j = square root of -1
>>r eal mi n % The smallest usable positive real number
>>r eal max % The largest usable positive real number
31 August 201128864
Matlab operators
+ Addition
- Subtraction
*
/ Division
\ Left division
^ Power
' Complex conjugate or transpose
( ) Specify evaluation order
31 August 201128864
7/28/2019 01_28864_Matlab_Syntax_E2011
11/24
11
A few tests!
Compare the results of:
>>56/ 8 and >>56\ 8
What is the result of the following statements?:
>> a=5, b=10
>> c=( a+b) 2+b
>> c=c+10
For complex numbers, try the following:
31 August 201128864
>>i '
Other Matlab symbols
>> prompt
. . .
, separate statements and data
% start a comment; the comment ends at end of line
; (1) suppress output
(2) used as a row separator in a matrix
31 August 201128864
: specify range, for example in a matrix
7/28/2019 01_28864_Matlab_Syntax_E2011
12/24
12
Outline
Introduction
Matlab syntax: useful commands to get started
Working with vectors and matrices
Matlab scripts and functions
31 August 201128864
Matlab programming control
File input / output
Definition of matrices in Matlab
Matlab treats all variables as matrices. For our purposes a matrix can bethought of as an array.
Vectors are special forms of matrices and contain only one row or onecolumn.
Scalars are matrices with only one row and one column
31 August 201128864
7/28/2019 01_28864_Matlab_Syntax_E2011
13/24
13
Definition of matrices in Matlab
Matrices and vectors are generated by enclosing a set of numbers insquare brackets
>>x = 1 2 3 4 5 6 7 8 9 10
The following statements are equivalent to the previous one:
>>x = 1: 1: 10
>>x = 1: 10
Defining a column vector:
>>y=[ 1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
31 August 201128864
y=x
Definition of matrices in Matlab
Defining a 3 by 3 matrix
>>a = [ 1 2 3; 4 5 6; 7 8 9]
Defining a 4 by 2 matrix
>>b = [ 1 2; 3 4; 5 6; 7 8]
Useful commands
>>si ze( a) % Find the size of the matrix a; 2 numbers will
be generated (first number of rows, then number of columns). Checkwith si ze( b)
31 August 201128864
>>l ength(y) % Find the length of the vector y
7/28/2019 01_28864_Matlab_Syntax_E2011
14/24
14
Selecting matrix elements
>>a = [ 1 2 3; 4 5 6; 7 8 9; 10 11 12] ;
>>aa=a( 4, 2) ;
= ,
>>ac=a( : , 2) ;
The colon operator by itself means that one selects all elements in onedirection. The colon separator can also be used to generate a list ofnumbers.
>>ad=a( 1: 3, 2) ;
>>ae=a( 2: end, 2) ;
31 August 201128864
Matrix algebra
>>x = 1: 10
>>y1 = 2 * x % Multiplies x by a constant
=
>>y3 = y1 + y2 % Adds the two vectors y1 and y2
Matrix multiplication
>>a=[ 1 2; 4 5; 7 8] ;
>>b=[ 0. 5 0. 2 2. 0; 4. 0 2. 0 5. 0];
>>c=a* b % Multiplies the two matrices and puts the result in a
new matrix c
31 August 201128864
7/28/2019 01_28864_Matlab_Syntax_E2011
15/24
15
Matrices, element by element operations
>>a=[ 1 2; 6 9]
=
>>x1=a. 3 % Takes the cube of each element in the square matrix a
>>x2=a 3 % Takes the cube of the matrix a
>>x3=a. *b % Multiplies element by element
a(i,j)*b(i,j) when size(a) = size(b)
31 August 201128864
>>x4=a* b % Matrix multiplication
Important!
In Matlab, performing calculations based on vectors is much faster thanwriting a loop construct!
Note that all functions in Matlab, for example sqrt(), will accept scalars,vectors or matrices as inputs
31 August 201128864
7/28/2019 01_28864_Matlab_Syntax_E2011
16/24
16
Outline
Introduction
Matlab syntax: useful commands to get started
Working with vectors and matrices
Matlab scripts and functions
31 August 201128864
Matlab programming control
File input / output
Matlab scripts
For tasks that are to be repeated:
Save them in a script and execute that script when needed
-,
To create an M-file:
Save all the repetitious Matlab statements in a text file with the .mextension.
To execute the script: enter the file name without the .m extension inthe Matlab command window
31 August 201128864
Matlab executes the commands found in the file
Scripts can:
Operate on existing data in the workspace
Can create new data on which to operate
Any variables created in a script remain in the workspace
7/28/2019 01_28864_Matlab_Syntax_E2011
17/24
17
Important!
Matlab has a built-in editor that can be used for creating m-files
>>edi t % opens up a new editor window.
Matlab may not find your M-files!
Windows machines: Matlab looks by default for your files in the Workfolder, a subfolder of the MATLAB installation folder.
When keeping files in your own directories.
Change the directory in the MATLAB Command Window to thedirectory where the M-file that you would like to use is located
OR add that directory with your files to the MATLAB searchath
31 August 201128864
Matlab functions
M-files that can accept input arguments and return output arguments
- .
Functions operate on variables within their own function workspace,separate from the workspace you access at the Matlab command prompt
Only output arguments of the function become available in theworkspace
31 August 201128864
7/28/2019 01_28864_Matlab_Syntax_E2011
18/24
18
Matlab function example
f uncti on y = squar e( x)
%
' '
%
% Ar gument s:
%
% x ( i nput ) val ue t o be squared
%
% y ( out put ) t he r esul t of t he squar e
%
31 August 201128864
y = x*x;
% end of squar e f unct i on
Calling a function from a script
SCRIPT
Define variables Define inputs to thefunction and call the function FUNCTION
Accept inputs
Perform calculations in
31 August 201128864
Present resultsextra calculationsplot / save to file
a local workspace
Send outputs to script
7/28/2019 01_28864_Matlab_Syntax_E2011
19/24
19
Outline
Introduction
Matlab syntax: useful commands to get started
Working with vectors and matrices
Matlab scripts and functions
31 August 201128864
Matlab programming control
File input / output
If statement
Conditionally execute statements
i f expr essi on
st at ements
end
Matlab evaluates the expression and, if the evaluation yields logical 1(true) or a nonzero result, executes one or more Matlab commandsdenoted here as statements.
31 August 201128864
When you are nesting ifs, each if must be paired with a matching end!
7/28/2019 01_28864_Matlab_Syntax_E2011
20/24
20
If statement
When using elseif and/or else within an if statement, the general form ofthe statement is:
i ex r essi on1
st atement s1
el sei f expr essi on2
st atement s2
el se
st atement s3
end
31 August 201128864
Switch statement
A means of conditionally executing code
Syntax
_
case case_expr
st atement , . . . , st at ement
case {case_expr 1, case_expr 2, case_expr 3, . . . }
st atement , . . . , st at ement
other wi se
st atement , . . . , st at ement
end
31 August 201128864
7/28/2019 01_28864_Matlab_Syntax_E2011
21/24
21
Switch statement, example
swi t ch a
case 0
' '=
case {1, 2, 3, 4}
di sp( ' a i s l ess than 5' )
case 6
di sp( ' a i s 6' )
other wi se
di sp( ' a i s out of r ange' )
end
31 August 201128864
For loop
Execute code a specified number of times
Syntax
=
st at ement s
end
Example:
a=[ ] ;
f or z=1: 5
even=2*z- 2;
a( z) =even
31 August 201128864
end
7/28/2019 01_28864_Matlab_Syntax_E2011
22/24
22
While statement
Repeatedly execute statements while condition is true
Syntax
st at ement s
end
repeats statements an indefinite number of times.
expression is usually of the form:
expression rel_op expression
where: rel_op is:
== (equal to), , =, or ~= (not
31 August 201128864
More advanced, but useful
Continue
Return
31 August 201128864
7/28/2019 01_28864_Matlab_Syntax_E2011
23/24
23
Example: use break to interrupt while loop
br eak is a very useful statement that allows you to exit a for or while
loop prematurely
Example:
a=10;
whi l e a>2
a=a/ 2;
i f a
7/28/2019 01_28864_Matlab_Syntax_E2011
24/24
Saving and loading workspace variables
>>save Saves all variables in the Workspace in matlab.mat
>>save FI LENAME Saves all Workspace variables to the binary
- .
>>save FI LENAME X Saves only the Workspace variable X to the
binary MAT-file named FILENAME.mat
>>l oad FI LENAME Retrieves data from the file
FILENAME.mat
If FILENAME has no extension, the .mat extension is assumed bydefault
31 August 201128864
Data in text files
>>save FI LENAME. t xt - asci i
Saves all Workspace variables to the ascii text file named FILENAME.txt
. -
Retrieves data from the file FILENAME.txt, which is assumed to be a tab-delimited ascii text file
31 August 201128864