fö 1introduction, matlab fundamentals - · pdf filefö 1introduction, matlab...
TRANSCRIPT
Pawel Herman
Fö 1 Introduction, Matlab fundamentals
DN1212 Numeriska metoder och grundläggande programmering
Pawel HermanKTH/CB
15 januari 2013
Pawel Herman
• Matlab programming for engineering
• Matlab environment
• Matlab fundamentals – variables, arrays
• Matlab fundamentals – operators, basic commands and functions
Lecture outline
2Fö 1 Introduction, Matlab fundamentals
Pawel Herman
• Computational approach with the use of numerical methodsfacilitates• finding approximate solutions at low costs• rapid prototyping, modelling and verification• scope for automated analysis• approaching large and complex systems without the need for
excessive simplifications• effective communication of various aspects of data/solutions to
customers etc. (flexibility)
• Matlab accommodates for these requirements and has mostwidely distributed engineering and technical applications.
Motivation for programming in engineering
3
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Fö 1 Introduktion. Matlabrepetition
Pawel Herman
• MATrix LABoratory – computer program to perform engineering and scientific computations
• It has its own programming/scripting language• interpreted high‐level language (like Java, Python, Perl etc.)• platform‐independence• relatively simple syntax with weak typing• IDE with debugger facilitates rapid development • extensive libraries of predefined functions in various domains• rich tools for device‐independent plotting
MATLAB can also be used in an interactive way, like a calculator.
Matlab... What is it?
4
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Fö 1 Introduktion. Matlabrepetition
Pawel Herman
• MATrix LABoratory – computer program to perform engineering and scientific computations
• It has its own programming/scripting language• interpreted high‐level language (like Java, Python, Perl etc.)• platform‐independence• relatively simple syntax with weak typing• IDE with debugger facilitates rapid development • extensive libraries of predefined functions in various domains• rich tools for device‐independent plotting
However, execution in Matlab can be relatively SLOW.
Matlab... What is it?
5
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Fö 1 Introduktion. Matlabrepetition
Pawel Herman
Desktop
Matlab environment, GUI
6Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Start button
Current directory
Command history
Workspace
Command window
Current path (by default data is saved and loaded from the current directory)
Interactive work
Ctrl+C
UNIX‐type of navigation(TAB, ↑)
clc
clear
Pawel Herman
Desktop
Matlab environment, GUI
7Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Editor
Help window
Figure window
Algorithms, scripts, functions as .m‐files(see also diary)
closeclf
Pawel Herman
Search path in Matlab, naming covention
8Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
via GUI Command window
addpath(path)
genpath(path/folder)
rmpath(path)
path2rc
savepath
editpath / pathtool
Priorities in search for variables and functionsIt is possible to check which version of a function is behind the function name.
which(’function_name’)
Pawel Herman
GUI help Interactive help
Help and basic debugging
9Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
• interactive in the Command windowlookfor function_namehelp function_name
>> help logLOG Natural logarithm.
LOG(X) is the natural logarithm of the elements of X.Complex results are produced if X is not positive.
See also log1p, log2, log10, exp, logm, reallog.
Reference page in Help browserdoc log
Searchable database
Main information windowCorresponding entries
Pawel Herman
Integrated editor‐debugger
Help and basic debugging
10Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
breakpoint current status
run programplace/remove a breakpointremove all breakpointsdo not step into a functiondebug inside a functionleave the current functionstop execution / exit debug mode
comments following %
help info in first two lines
Pawel Herman
Integrated editor‐debugger
Help and basic debugging
11Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
breakpoint current status
run programplace/remove a breakpointremove all breakpointsdo not step into a functiondebug inside a functionleave the current functionstop execution / exit debug mode
comments following %
help info in first two lines
PROBLEM: Inner matrix dimensions must agree!
Pawel Herman
Integrated editor‐debugger
Help and basic debugging
12Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
breakpoint current status
run programplace/remove a breakpointremove all breakpointsdo not step into a functiondebug inside a functionleave the current functionstop execution / exit debug mode
comments following %
help info in first two lines
Additional features• evaluate selection• evaluate cell
Pawel Herman
• Fundamental unit of data is array (scalar, vector or matrix)
• symbolic use as mathematical variables in expressionsavg_velocity = avg_distance / travel_time;
• they store intermediate values of calculations (ans)
• assign meaningful names to variables (Matlab is case‐sensitive)
Fundamental concepts – variables
13Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
[nrows,ncols] = size(array)
size(a) = [3, 2], numel(a)=6
size(b) = [1, 3], length(b)=3
size(c) = [3, 1], length(c)=3
Pawel Herman
• Data types (weak typing convention)
Matlab variables
14Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
• No need to declare the type of variables since the data assigned decides about it– code is easily reusable but also more susceptible to bugs that are hard to track.
• Type casting allows for different interpretations of the same data.
• Memory vs precision trade-off.
int8 - 8 bit –128..127int16 -16 bit –32 768..32 767uint8 – unsigned int 8bit 0..255uint16 - unsigned16 bit 0..65 535
Type casting
d1 = 32; d2 = uint8(32); whos d1 d2
Name Size Bytes Classd1 1x1 8 double arrayd2 1x1 1 uint8 array
Pawel Herman
• Predefined variables
• pi π (15 digits)
• i, j complex imarinary unit
• inf this represents machine infinity
• nan not‐a‐number as a result mathematically undefined operations, e.g. 0.0/0.0 or inf‐inf
• eps the smallest difference between two numbers that can be represented on the computer
• ans variable used to store the result of the most ecent expression
Matlab variables
15Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
1−
Pawel Herman
• Notation, indexing
Array notation, access and initialisation
16Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
1 4 7 10 13 16
2 5 8 11 14 17
3 6 9 12 15 18
Matrix a
size(A)=[3, 6]3 rows
6 columns
a(2, 4) = 11; this is equivalent to a(11)=11;
row column 1D index2D index
One-based index in Matlab, i.e. the first row/column has index 1 (not 0 as in C)
Pawel Herman
• Multidimensional matrix – a natural extension of a 2D case
Array notation, access and initialisation
17Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
1 22 0 13 9 8
2 5 8 11 14 17
8 6 9 12 15 18
a(: , : , 1) = [1 4 7 10 13 16; 2 5 8 11 14 17; 3 6 9 12 15 18]
3D matrix can be seen as an array of 2D matrices
6 4 7 1 21 6
2 5 8 11 14 17
3 6 9 12 15 18
9 6 17 31 5 3
0 5 8 11 14 17
7 6 9 12 15 18
1 4 7 10 13 16
2 5 8 11 14 17
3 6 9 12 15 18
Pawel Herman
• Assigning values• [ ] is an empty array• If a = [ ] then matrix defined as a = [a, b] or a = [a; b] is the same as b this can be used to increment a vector or matrix with new values (see for‐loops)
• ; splits data into rows, e.g. a = [4, 9, 0, 1, 5; 0 1 2 6 7; 3 8 3 4 2];
• end function, a(2, 3:end) = [2 6 7]
Array notation, access and initialisation
18Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
⎥⎥⎥
⎦
⎤
⎢⎢⎢
⎣
⎡=
243837621051094
a Here it corresponds tosize(a,2) = 5
Pawel Herman
• Assigning values• [ ] is an empty array• If a = [ ] then matrix defined as a = [a, b] or a = [a; b] is the same as b this can be used to increment a vector or matrix with new values (see for‐loops)
• ; splits data into rows, e.g. a = [4, 9, 0, 1, 5; 0 1 2 6 7; 3 8 3 4 2];
• end function, a(2, 3:end) = [2 6 7]
• colon : for indexing and to refer to all elements,
a(1:2, :) = [4 9 0 1 5; 0 1 2 6 7]
Array notation, access and initialisation
19Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
⎥⎥⎥
⎦
⎤
⎢⎢⎢
⎣
⎡=
243837621051094
a
Equivalent to 1 : size(a,2)
Pawel Herman
• Initialisation• zeros(n), zeros(n, m) n x n (or n x m) matrix of zeros
• zeros(size(a)) matrix of zeros of the sime siz as matrix a
• ones(n), ones(n, m) n x n (or n x m) matrix of ones
• ones(size(a)) matrix of ones of the sime size as matrix a
• eye(n) identity matrix of size n x n• a : incr : b vector with the first value a and then a+incr,
a+2*incr until it is greater or equal to b, e.g.3 : 4 : 20 = [3 7 11 15 19]
• linspace(a, b, n) vector linearly spanning interval [a, b] with n elements, e.g.linspace(4, 16, 4) = [4 8 12 16]
Array notation, access and initialisation
20Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Pawel Herman
• Concatenation of vectors and matrices (dimension matters)
Matrix manipulations
21Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
These components eventually constitute subarrays.
Pawel Herman
It is possible to access a set of array elements at the same time, either to select a subset of data for further processing
a = [1 2 7 4; 2 8 9 3; 1 6 2 -7] (3 x 4 array)a(1:2,1:3) = 1 2 7
2 8 9or .....
Subarrays and indexing
22Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Pawel Herman
It is possible to access a set of array elements at the same time, either to select a subset of data for further processing
a = [1 2 7 4; 2 8 9 3; 1 6 2 -7] (3 x 4 array)a(1:2,1:3) = 1 2 7
2 8 9or to set their values (either with an array of the same size as the target subarray:
If b = [3 2 1; 0 2 0], THEN a(1:2,1:3) = b;
alternatively, scalar value can be to used to set the entire subarray :
a(1:2,1:3) = 1, which imples a = [1 1 1 4; 1 1 1 3; 1 6 2 -7]
Subarrays and indexing
23Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Pawel Herman
It is possible to access a set of array elements at the same time, either to select a subset of data for further processing
a = [1 2 7 4; 2 8 9 3; 1 6 2 -7] (3 x 4 array)a(1:2,1:3) = 1 2 7
2 8 9
Do not forget that you can always use logic variables for indexing arrays, e.g.
a(a<0) = 0 (sets to 0 all elements of a that are negative in the beginning),
More explicitly, a( logical([1 1 1 0; 1 1 1 0; 0 0 0 0]))
Subarrays and indexing
24Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Pawel Herman
• Data input• loading data
– load(filename,’var1_name’,..,’varN_name’) or load filename to recover all variables– data can be read binary, ASCII or as Matlab format (it will be covered later on)
• input from the keyboard– val = input(’Please enter the value:’);– an additional parameter ’s’ converts the input value into string format
– user is prompted in the Command window
• import via ImportWizard or command line(mat‐type or ASCII data)
Matlab data
25Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Pawel Herman
• Data output• display (the role of ;)
– format short / long / short e / long e / compact / loose– disp (numerical and char strings; see int2str and num2str)– C‐style sprintf with a formatting string, sprintf(’Result = %f for %d’ trials, 2.3, 10)
• saving data– save(filename,’variable_name’) or save filename to save the entire workspace– data can be written binary in Matlab format or ASCII (it will be covered later on)
• graphical presentation (e.g. plot)x = 0 : 0.1 : 10; y = x.^2;plot(x,y);
Matlab data
26Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Pawel Herman
• plot function• figure and plot(x, y, ’k.-’)• multiple plots: plot(x1, y1, ’.-g’, x2, y2, ’--r’)• alternatively: plot(X, Y) plots columns in X vs. columns in Y• hold on, hold off can be used to control whether consecutive plots
should be made in the same figure
• fplot(’3*sin(2*x)+x^3‐2*x^2’, [‐0.5, 3.5]) for plotting functionalexpressions (compare with eval(’functional_expression’))
• figure and plot properties can be set in scripts (xlim, xlabel, title etc.)
• figures and their properties can be further modified in the Figurewindow (especially Insert and Tool menu)
Plotting Matlab data
27Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Pawel Herman
• Most common algebraic operators
element‐wise matrix operators
A + B addition (a+b)
A – B subtraction (a-b)
A .* B multiplication elem by elem (a*b) A * B matrix multiplication
A ./ B right division of elements (a/b) A / B right matrix division A * B-1
A .\ B left division of elements (b/a) A \ B left matrix division A-1 * B
A .^ B exponentiation
A .’ transpose A’ complex conjugate transpose
Fundamental concepts – operators
28Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
+ operations involving scalars
Pawel Herman
• Most common logic operators (result in TRUE=1 or FALSE=0)
>, >= greater, greater or equal to
<, <= less, less or equal to
== equal to
~= different from
~ NOT
&, && AND
|, || OR
Fundamental concepts – operators
29Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Operators are applied in order according to their priority (safe use of brackets)
Pawel Herman
• [maxval, index]=max(A) [minval, index]=min(A)
• [index] = find(A) or [r, c] = find(A) all(A) any(A) sum(A)
• size(x) numel(x) length(x) reshape(x, r, c) isempty(x)
• round(x) ceil(x) floor(x) fix(x)
• char(x) double(x) int2str(x) num2str(x) str2num(x)
• abs(x) angle(x) conj(x) real(x) imag(x)
• setdiff(a,b) intersect(a,b) union(a,b) ismember(a,b)
• [y, xind] = sort(x) [y, xind, yind] = unique(x)
• Common mathematical functions: sin(x), cos(x), ...., exp(x), log(x), sqrt(x), mod(x,y), mean(x), std(x), var(x)
Common built‐in functions
30
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)
Fö 1 Introduction, Matlab fundamentals
Pawel Herman
• In summary• Matlab can be used both interactively and non‐interactively in the form
of scripted algorithms implemented in Matlab programming language• Array are a fundamental unit of stored information (variables)• Matlab allows for rapid prototyping and finding numerical, symbolic and
graphical solutions to engineering problems• It offers a plethora of built‐in ready‐to use functions
• What have we learnt today?• How to use the Matlab environment, GUI.• How to define variables and perform basic operations on arrays.• How to use interactive command line and simple M‐scripts.• How to graphically present data in Matlab (plotting basics).
Summary and recapitulation
31Fö 1 Introduction, Matlab fundamentals
• Matlab programming, introduction• Matlab environment• Fundamentals (variables, operators, basic functions)• Summary