Upload
fiterlinge-sousa
View
217
Download
0
Tags:
Embed Size (px)
Citation preview
Mathematics of photonic crystals
Tutorial: An introdiuction to MATLAB
Dagmar Roth(Karlsruhe Institute of Technology)
Intensive Programme / Summer School Periodic Structures in Applied MathematicsGttingen, August 18 31, 2013
This project has been funded with support from the European Commission. This publication [communication] reflects the views only of the author, and the Commission cannot be held responsible for any use which may be made of the information contained therein.
Grant Agreement Reference Number: D-2012-ERA/MOBIP-3-29749-1-6
Tutorial:
An introduction into
MATLAB
2MATLAB Overview
mathematical functions for linear algebra, statistics, Fourier analysis, numerical integration, differentiation, ordinary differential equations, and more fast execution of vector and matrix calculations no low-level administrative task such as declaring variables, specifying data types and allocating memory necessary (unlike in C(C++) or Fortran) built-in 2-D and 3-D plotting functions Many additional and useful toolboxes: symbolic math, parallel programming, partial differentail equations, optimization, interval analysis (INTLAB), ...
http://www.mathworks.com/products/matlab/
MATLAB is a high-level language and interactive environmentfor numerical computation, visualization, and programming. Using MATLAB, you can analyze data, develop algorithms, and create models and applications. The language, tools, and built-in math functions enable you to explore multiple approaches and reach a solution faster than with spreadsheets or traditional programming languages, such as C/C++ or Java.
3Example multiplication of a matrix A and a vector x
for(i=0; i
MATLAB's Main Window
Current Folder
Workspace: Shows assigned variables
Command Window: Execution of calculations, to call commands and functions
Command History:Lists all previously called commandsFile details
MATLAB Product Help
5>> a=1; b=2; c=a+bc = 3
Basics: In- and Output
Variables a and b are initialized (no prior declaration), sum of a and bis calculated and stored in variable c.
Semicolon after formula: Result is not displayedWithout semicolon the result is displayed
>> a=1, b=2.5, c=a+ba = 1b = 2.5000c = 3.5000
>> a=1; b=2; c=a+b;>>
In case that all formulas end withsemicolon, nothing is displayed.
Enter Key
6By adding three dots in the end of a line, input canbe continued to the next line.
>> a1=1; a2=2; a3=3; a4=4; ...a5=5; a6=6; a7=7; a8=8; ...a1+a2+a3+a4+a5+a6+a7+a8ans = 36
If no variable is initialized for a result, the expression ans = is displayed . You can use the command disp if you want to display a result without ans=.
>> a1=1; a2=2; a3=3; a4=4; ...a5=5; a6=6; a7=7; a8=8; ...disp(a1+a2+a3+a4+a5+a6+a7+a8) 36
Variables
The first character of a name of a variable should be an alphabetic character and the variable-name should be different from the name of MATLAB functions (or predefined variables) Names of variables are case sensitive, i.e. a capital letter is distinguished from a small letter Types of a variables do not need to be specified: In assignment, MATLAB does not distinguish between integers and real numbers with decimal point All initialized variables are listed in Workspace-window: Variables can easily be saved for later sessions or imported from saved data
8Special variables
In order to express some special numerical values orspecial matrices, some names are fixed as follows:
Name Meaning
pi Inf, inf infinity,i, j, 1i imaginary uniteps machine epsilon ( minimal satisfying 1+>1 ) eye(n) unit matrix of dimension nones(n,m) matrix (n rows, m columns) whose all elements are 1 zeros(n,m) matrix (n rows, m columns) whose all elements are 0NaN, nan Not a Numberrealmin the smallest positive floating point number which is expressible in a computerrealmax the greatest positive floating point number which is expressible in a computer
1
9If you substitute a different value for these special variables, then it is maintained until you use the clear command. Especially i, j are often used as variables in loops, so you must take care in case you use the imaginary unit.
>> pians = 3.141592653589793>> pi=3pi = 3>> 10*pians = 30>> clear pi>> 10*pians = 31.415926535897931
1 Kings 7,23
And he made a molten sea, ten cubits from the one brim to the other: it was round all about, and his height was five cubits: and a line of thirty cubits did compass it round about.
Perimeter=30Diameter=10 => pi=3
10
complex variables
>> z1=1+2*iz1 = 1 + 2i>> z2=3+4*jz2 = 3 + 4i>> z1+z2ans = 4 + 6i
Once a value is substituted for i , then you cannot use i for imaginary unituntil you use clear command in order to restore it.
>> i=2; z2=5+6*iz2 = 17>> clear i>> z2=5+6*iz2 = 5 + 6i
11
Change of displayed accuracy
>> x=1/3x = 0.3333>> format short e; xx = 3.3333e-001>> format long; xx = 0.33333333333333>> format long e; xx = 3.333333333333333e-001>> format hex; xx = 3fd5555555555555
short (default) fixed point format with 5 digitsshort e floating point number with 5 digitslong fixed point format with 15 digitslong e floating point number with 15 digitshex hexadecimal number short g, long g best of fixed or floating Point number with 5 or 15 digits, resp.
If you change the displayed accuracy using format, it is maintained unlessyou change it again.
Note that this does not affect computational accuracy
12
Useful commands and control key help command
You can check how to use some command as follows:>> help command
>> help format FORMAT Set output format. FORMAT with no inputs sets the output format to default. For float variables, the default is FORMAT SHORT. FORMAT does not affect how MATLAB computations are done. Computations on float variables are done in appropriate floating point precision, no matter how those variables are displayed. FORMAT SHORT and LONG do not affect the display of integer variables. FORMAT may be used to switch between different output display formats: FORMAT SHORT Scaled fixed point format with 5 digits. FORMAT LONG Scaled fixed point format with 15 digits for double FORMAT SHORT E Floating point format with 5 digits. FORMAT LONG E Floating point format with 15 digits for double FORMAT SHORT G Best of fixed or floating point format with 5 digits. FORMAT LONG G Best of fixed or fl. point format with 15 digits for double
how to useformat
13
The statement which starts with % in your original M-filecan be also displayed by the help command.For example, if the file flow.m has the following content,% Program to plot the solutionfunction [f] = flow(K);
then help command gives us the following output.
>> help flow Program to plot the solution
You had better add some appropriate comment in the beginningof your M-file in order to remember which kind of program it is.
14
lookfor commandYou can search for a keyword in predefined matlab functions and commands. For example, if you want to find functions and commands involving max then you may input lookfor max in the command line.
>> lookfor maxrandomc Complex random numbers in M+i*M with M=[min,max], default [-1,+1]random Random numbers in [min,max], default [-1,+1]Longprecision Sets/gets maximum precision for long number arithmeticmaxNumCompThreads controls the maximum number of computational threadsNamelengthmax Maximum length of MATLAB function or variable name.bitmax Maximum double precision floating point integer.intmax Largest positive integer value.realmax Largest positive floating point number.max Largest component.runtrackmm demonstrates using FMINIMAX with Simulink.dfildemo minimax Optimizationpdenanmx NaN protected maximum.hp2dmax [alpha,wm,theta,L,P,ejtheta] = hp2dmax(w1,w2,w)d2dmax [b,tm,psi,L,P,ejpsi] = d2dmax(t1,t2,theta)dhinfric [gopt,K,X1,X2,Y1,Y2] = dhinfric(P,r,gmin,gmax,tol,options)
Some functions or commands are displayed with simple explanations.
15
arrow key and control key
In MATLAB the command-history is preserved in the memory,you can use the arrow keys to call previous commands
, search in command historyx( , search in command history for commands starting with
x( only , Move right /left for one letter
Delete Delete the letter to the left of cursor Ctrl-D Delete the letter to the right of cursorCtrl-A Go to to beginning of the lineCtrl-E Go to to end of the lineCtrl-U Delete current lineCtrl-K Delete all letters from current position to the end of the line
16
Arrays
vector one dimensional arraymatrix two dimensional array
An index of an array must be a positive integer starting from 1.
>> x=[1 2 3]x = 1 2 3>> x'ans = 1 2 3>> y=[1;2;3]y = 1 2 3
row vector (also x=[1,2,3])
column vector is expressedadding .
Since semicolon expresses theend of a row, a column vectorcan also be generated like this.
17
There are other methods to generate vectors.
Specify the initial value, increment and last value with colon
>> x=[1:2:7]x = 1 3 5 7>> x=[1:4]x = 1 2 3 4
From 1 to 7 incrementing by 2
If the increment is 1 then itcan be omitted.
Specify the initial value, last value and the number of element using the function linspace
>> y=linspace(1,3,5)y = 1 1.5 2 2.5 3
Generate 5 elementsfrom 1 to 3 with equalspace.
18
>> A=[1 2 3; 4 5 6]A = 1 2 3 4 5 6>> A'ans = 1 4 2 5 3 6>> a=A(:)a = 1 4 2 5 3 6
matrix with 2 rowsand 3 columns
A stands for the transposedmatrix of A (if A is real). (A complex: A' is the complexconjugate transpose of A)
transformation of two dimensional array to onedimensional array. Columns of the matrix arewritten into vector sequentially
19
Access to single elements of an array
x(k): k-th element of one dimensional array x.A(i,j): (i,j)-element of two dimensional array A.
>> x=[1 2 3]x = 1 2 3>> x(2)ans = 2>> A=[1 2 3;4 5 6]A = 1 2 3 4 5 6>> A(2,2)ans = 5>> A(5,5)??? Index exceeds matrix dimensions
An error code isdisplayed if youcalled anon-existing element.
Access to subarrays
x(k:l): subvector A(k:l,n:m): submatrix
A(:,m): gives the m-th column of A (column vector)A(n,:): gives the n-th row of A (row vector)
(Aij) kiln jm
( xi)kil
>>x=[1:7]x = 1 2 3 4 5 6 7>> x(3:5)ans = 3 4 5
>> A=[1,2,3;4,5,6]A = 1 2 3 4 5 6>> A(:,1)ans = 1 4>> A(1,:)ans = 1 2 3
21
Operations, Mathematical functions operations
formula expression in MATLAB
a b+a b-ab/a bba
a + b
a - b
a * b
a / b
a^b
22
comparison operation
formula expression in MATLAB
and
or
a < b
a b
a >= b
a == b
a ~= b
&
|
true: 1 false: 0
ab
ab
ab
ab
a=b
ab
23
Example:
>> a=1; b=[2;3]; A=[1 2;3 4]; B=[5 2; 3 5];>> a>0ans = 1>> b==2ans = 1 0>> A==Bans = 0 1 1 0>> A> A~=Bans = 1 0 0 1
24
element-wise operations
For example, for two matrices
>> A*B
gives
then replace * by .* as follows:
>> A .* Bans = 1 4 6 4
If you want to compute the matrix (element-wise operation)
A=1 23 4 B=1 22 1
AB=5 411 10aijbij
25
formula expression in MATLAB
a + b
a .* b
a ./ b
a .^ b
Example for vectors
a=a1 ,, an , b=b1 ,,bn
a1b1 ,, anbn a1b1 ,, anbn a1 /b1 , , an /bn a1b1 , ,anbn
26
Mathematical functions
Various mathematical functions are available in MATLAB.There are also many mathematical functions in each toolbox.Use the help command to understand their handling.
Basic mathematical functions
abs absolute valuesqrt square rootlog natural logarithmexp exponential functionreal real part of a complex variableimag imaginary part of a complex variableangle argument of a complex variableconj conjugate of a complex variable
27
Basic statistical functions
sum sum of elementsmean mean valuecov covariancecorrcoef correlation coefficientsort sort in ascending or descending orderprod product of elementscumsum cumulative sumcumprod cumulative product
trigonometric functions
sin sin(x)cos cos(x)tan tan(x)asinacosatansinh sinh(x)cosh cosh(x)
matrix functions
inv inverse matrixdet determinantlu LU decompositionchol Cholesky decompositionnorm (various) norms cond condition numbereig eigenvalues
etc
sin1 xcos1 xtan1 x
28
Branch, Loopif statement
if expression1 statement1elseif expression2 statement2else statement3end
or
if expression1, statement1elseif expression2, statement2else statement3end
elseif and else can be omitted.
29
Example
>> x=-1;>> if x>0, y=1; elseif x==0, y=0; else y=-1; end>> yy = -1
If x does not have any value then the following error messageappears:
??? Undefined function or variable 'x'.
30
Loop
Several program statements can be repeatedly executed in a loop. The variable controlling the repetition is called loop variable.
There are two types of loops.
To specify the number of iterations
To repeat a group of statements as long as a certain condition is satisfied
for
while
31
for
for loop variable = range of the loop variable statementend
>> s=0;>> for i=1:10 s=s+i; end;>> disp(s) 55
i: loop variable, iteration number is 10
>> s=0;>> for i=10:-1:1 s=s+i; end;>> disp(s) 55
If you want to execute the iterationconversely then these expressionsare available.
32
A loop variable can be incremented by a predefined value in each step:
>> s=0;>> for i=2:2:10 s=s+i; end;>> disp(s) 30
Loop variable i is set as even number.( i starts at 2, is incremented by 2 in each step and ends at 10 )
>> s=0;>> for i=10:-2:2 s=s+i; end;>> disp(s) 30
Converse version
>> v=[1 10 100];>> for k=v disp(k) end 1 10 100
vector can also serve as range for loop variable
33
The continue command is used when you want to go tothe next iteration of the loop, and the break command is used when you want to terminate the execution of the loop.
>> s=0;>> for k=[1 -1 2 -2 3 -3 4 -4 5 -5] if k5, break; end disp(s); end 1 3
If k is negative then go to next iteration.
If s is greater than 5,quit the loop.
continue and break
34
while
while condition statementend
>> a=10;>> while a>=1 a=a/2; disp(a) end 5 2.50000000000000 1.25000000000000 0.62500000000000
The commands within the loop are executed while a is greater than or equal to 1.
break and continue can be usedas in the for-loop.
35
Script and functionM-files can be scripts and functions , both are named ***.m.
script file: consisting of some commands
You can execute it by typing its file-name.
function file: consisting of definition for function
The name of the file is the name of the function.
You can use a function/script without any declaration if the folder containing the m-file is on your MATLAB-path. To add a folder:
File Set Path Add Folder
Exercise:
Write a script fibo.m, that computes all Fibonacci numberssmaller than 1000 and stores them in an array. Display the array.
Hint: If f=[1] is an array, the assignment f(2)=2 automatically increases its size
37
% An M-file to calculate Fibonacci numbersf=[1 1]; i=1;while f(i)+f(i+1)> fibo Columns 1 through 11 1 1 2 3 5 8 13 21 34 55 89 Columns 12 through 16 144 233 377 610 987
fibo.m
Size of array is increased automatically
38
Example of function
% Function to compute the sum and difference% of two real numbersfunction [wa,sa]=cal(a,b)wa=a+b; sa=a-b;
Definition of function
In the beginning of M-file, declare the function with in- and output parameters as follows:
function [list of output] = function-name(list of input)
cal.m
>> x=1; y=2;>> [c,d]=cal(x,y)c = 3d = -1
Exercise:
Modify fibo.m into a function, that computes all Fibonacci numberssmaller than some input value M, stores them in an array f andreturns f
40
% An M-file to calculate Fibonacci numbersfunction f=fibo(M)f=[1 1]; i=1;while f(i)+f(i+1)> f=fibo(1000)f = Columns 1 through 11 1 1 2 3 5 8 13 21 34 55 89 Columns 12 through 16 144 233 377 610 987
fibo.m
41
Global variables
function y=func(x)global a b cy=a*x^2 + b*x +c;
global a b ca=1; b=2; c=3;x=1;y=func(x);disp(y)
cal2.m func.m
The common variables between script and function can be declared as global variables.
>> cal2 6
Example
42
Measurement of elapsed timeThe elapsed time between tic and toc can be measured.
>> tic;A=rand(1000,1000);toc;elapsed_time = 0.078000
>> tic;A=rand(1000,1000);time=toc;disp(time); 0.07800000000000
elapsed time can be storedin a variable.
43
Vectorization, High-speed
Vectorization
Some tricks can speed up computations!
>> clear;tic;for j=1:1000 for k=1:1000 A(j,k) = sin(j)+cos(k); endendtoc;Elapsed time is 1.003845 seconds.
Try to optimize computation time.
Copy code into an m-file:MATLAB's code analyzer will give you hints!
Example:
44
>> clear;tic;A=zeros(1000,1000);for j=1:1000 for k=1:1000 A(j,k) = sin(j)+cos(k); endendtoc;Elapsed time is 0.112592 seconds.
Step 1
Add this line
In MATLAB arrays do not need to be declared in advance.However, resizing an array in a loop needs time, due to the allocation of memory in each iteration.In the above example, zeros(1000,1000) reserves all needed memoryat once (before the loop).
45
>> clear;tic;A=zeros(1000,1000);j=[1:1000];sinj = sin(j);for k=1:1000 A(j,k) = sinj+cos(k);endtoc;Elapsed time is 0.010881 seconds.
Step 2 (vectorization)
Treat row as vector
46
Graphics in 2 dimensions ezplot displays the graph of function
ezplot(f(x))
ezplot(f(x), [a,b])
ezplot(f(x,y))
ezplot(f(x,y), [a,b])
ezplot(f(x,y), [a,b,c,d])
ezplot(x(t)', 'y(t)) Plot x=x(t), y=y(t) in
ezplot(x(t)', 'y(t), [a,b])
Plot f(x) in
Plot f(x) in
Plot f(x,y)=0 in
Plot f(x,y)=0 in
Plot f(x,y)=0 in
Plot x=x(t), y=y(t) in
2x2
axb
2x , y22x , y2
ax , yb
axb,c yd
0t2
atb
47
plot 2D plot with vector data
>> x=linspace(0, 2*pi, 100);>> plot(x, sin(x));
Example
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
>> x=linspace(0, 2*pi, 100);>> plot(x, sin(x), x, cos(x));
plot(x,y) plots vector x versus vector y
48
When ezplot or plot is executed, the graph is displayed in a window named Figure 1.
Another call of ezplot/plot erases the graph.
Figure 1 Figure 2
>> x=linspace(0, 2*pi, 100);>> figure(1); plot(x, sin(x));>> figure(2); plot(x, cos(x));
In this way, two graphsare displayed in Figure 1and Figure 2 respectively.
49
The command hold on is useful when you want todisplay some graphs in the same Figure.(The command hold off is used to quit it.)
>> x=linspace(0, 2*pi, 100);>> plot(x,sin(x));>> hold on;>> plot(x,sin(2*x));>> plot(x,sin(3*x));
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
sin( ), sin(2 ), sin(3 )x x xThe graphs of
are displayed in one Figure.
50
Some options in graphics
b blue . dot - solid lineg green o circle shape : dotted line r red x x shape -. chained line c cyan + plus shape -- broken line m magenta * star shape (none) no liney yellow s squarew white d diamond shapek black v triangle ^ inverted triangle < triangle (left direction) > triangle (right direction) p pentagon h hexagon
plot(x, y, s) 's' is specified as follows:
51
>> x=linspace(0, 2*pi, 20);>> plot(x, sin(x), 'r+:')
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
520 1 2 3 4 5 6 7
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
>> x=linspace(0, 2*pi, 20);>> plot(x, sin(x), 'r+:', x, cos(x), 'kd--')
53
>> x=linspace(0, 2*pi, 50);>> plot(x, sin(x), 'rv', 'MarkerSize', 5)
The size of marker can be specified by MarkerSize
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
>> x=linspace(0, 2*pi, 50);>> plot(x, sin(x), 'rv', 'MarkerSize', 10)
540 1 2 3 4 5 6 7
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1Plot of Sin(x)
>> x=linspace(0, 2*pi, 100);>> plot(x, sin(x)); title('Plot of Sin(x)');
The title can be added by title(text) in upper part of the graph
Title
55
Graphics in 3 dimensions
02
46
810
0
2
4
6
8
10-2
-1.5
-1
-0.5
0
0.5
1
1.5
2
>> t=linspace(0,10,40);>> [x,y]=meshgrid(t,t);>> z=sin(x)+cos(y/2);>> mesh(x,y,z);
Additionally ezplot3 etc. Check via help ezplot3.
56
Variables: Save and Load
To save variables you can use
>> save filename
A file named filename.mat is created which saves all variables from workspace. Using
>> load filename
variables in filename.mat are imported into workspace
If you omit the file name after save command then all variables are saved in a file named matlab.mat (load restores data from matlab.mat)
Alternatively you can use the buttons Save and Import dataon top of workspace window
57
e.g. >> whos Name Size Bytes Class
A 100x100 80000 double array B 200x200 320000 double array fid 1x1 8 double array i 1x1 8 double array j 1x1 8 double array z 1x1 16 double array (complex)
Grand total is 50004 elements using 400040 bytes
>> save variable>> clear>> whos>> load variable>> whosName Size Bytes Class
A 100x100 80000 double array B 200x200 320000 double array fid 1x1 8 double array i 1x1 8 double array j 1x1 8 double array z 1x1 16 double array (complex)
Grand total is 50004 elements using 400040 bytes