Upload
others
View
12
Download
2
Embed Size (px)
Citation preview
Matlab Course
Anna Kristine Wahlin
Department of Geophysics, University of Oslo
January 2003
Matlab Course – p.1/??
Day 1
Day 1 – p.2/??
Matlab
Matlab is a program for scientific computing and visualiza-
tion. Its strength is that it is easy to learn, and you can use
advanced mathematical methods and visualization tools
right from the start. For some applications it is directly in-
appropriate to use Matlab. Today’s lectures are concluded
with some tips concerning Matlabs usefulness for different
computations. There are large improvements in the latest
version of Matlab (6.5) in particular with regard to comput-
ing speed. Matlab 6.5 is comparable in speed to Fortran
and C/C++.Day 1 – p.3/??
Today
� Getting started (demonstration)
� Linear algebra with Matlab
� Creating scripts and functions
� Optimalization
Day 1 – p.4/??
Day 2: Using Matlab
� Data treatment
� Mathematical methods
� Differential equations
Day 1 – p.5/??
Day 3: Visualization
� Creating different types of illustrations
� Interactive editing
� Handle graphics
� Movies
Day 1 – p.6/??
Recommended books
� Introduction to Matlab 6 by Etter, Kuncicky and Hull.Prentice Hall, 2002 (239 NOK, paperback)
� Numerical analyses and Graphic visualization withMatlab (second edition) by Nakamura. Prentice Hall,2002 (879 NOK, hardback)
� Mastering Matlab 6 - A Comprehensive Tutorial andReference by Hanselman and Littlefield. PrenticeHall, 2002 (459 NOK, paperback)
Day 1 – p.7/??
Getting started
A summary of the demonstration is given as hand-out (Get-
tingStarted.pdf). A list of all the commands and Matlab re-
sponses can be found in Demo.pdf.
Day 1 – p.8/??
What is an m-file?
� An m-file is a file with extension .m
� It can be used to store commands
� Matlab reads and executes the commands in anm-file if you type the name of the file in the commandwindow
Day 1 – p.9/??
Different ways of creating m-files
� Use an ordinary text editor and save the file asfilename.m
� Choose ’new file’ under the File Menu
� If you have already executed the commands ’byhand’, you can mark them in the history window andthen right-click. The option ’make m-file’ thenappears
Day 1 – p.10/??
Example (myfile.m)
clear % clears the workspace
x = linspace(-pi/2,pi/2,50); % Creates vector x
y = linspace(-pi/2,pi/2,50)’; % Creates vecor y
z = exp(-y.ˆ2)*exp( -x.ˆ2).*(sin(4*y)*cos(4*x));% Calculates the matrix z
mesh(z) % Draws a mesh plot of z
Day 1 – p.11/??
Matrix Laborations
� Basic matrix functions
� Creating functions
� Loops and logical tests
Day 1 – p.12/??
Matrix operations
� Besides the elementary functions that are defined forscalars (and operate element-wise on the matrix)there are several functions that are specific formatrices. The most important of these are given ashand-out. A few will now be demonstrated using alinear equation system as example.
Consider the system of linear equations given by
� �� � � �� � �� � ��
� �� � � �� � �� � �
�� � � �� � � �� � �
(1)
Day 1 – p.13/??
Using matrix notation the above can also be written
� � � ��� (2)
where
� ��
��� � �
� � �
� � ��
� ��
����
����
�� �
���
� ��
�
� (3)
The solution to the system is given by
� � �� � � � (4)
Day 1 – p.14/??
In Matlab there are two ways of solving this problem.
� Calculate the inverse of
� � �� ��
, then find � byleft-multiplication of
�
with
� � �
� Left-division of
�
with
�In the first case the function inv(A) is used to find theinverse. This is then multiplied by b. The Matlab code forthis operation isA = [3, 2, 1; 2, 3,1; 1, 2, 3];b = [39; 34; 26];x = inv(A)*b
In the second case left- division is performed straightaway with the commandx = A\b
One option is faster than the other Day 1 – p.15/??
Example
solvetime.mA = rand(1000,1000); % Creates a random
% matrix Ab = rand(1000,1); % Creates a random
% vector b
det(A) % Calculates the determinant% of A
tic, % Starts the time-watchx = inv(A)*b; % Solves the systemtoc % Stops the watch
tic, y = A\b; toc % Solves and times the system% with left division
Day 1 – p.16/??
Example
compres.mclear % Clears the workspaceload example % Loads matrix A and vector b
% from file example to the% workspace
x1 = inv(A)*b; % Calculates x using the% inverse
x2 = A\b; % Calculates x using% left-division
ind = 1:length(x1); % Creates index for the plotplot(ind,x1,ind,x2) % Plots the two solutions
Day 1 – p.17/??
Over- and under-determined equationsystems
Matlab can also handle over- and under-determinedequation systems. The optimal solution (in a least-squaresense) is then found.overdet.m
clear % Clears the workspace
A = rand(1000,999);b = rand(1000,1); % Creates a vector b of
% random numbers
tic, x = A\b; toc % Solves the system with% a least-square fit,% and times the operation
Day 1 – p.18/??
When you write something in Matlab’s command window,the following things are checked in turn:
� 1. Is there such a variable in the workspace?
� 2. Is there an m-file called that thing in the currentdirectory?
� 3. Is there an m-file called that somewhere else?
When Matlab searches for the m-file it looks in specific fold-
ers, its search path. If the folder is not added to the path
Matlab can not run your script.
Day 1 – p.19/??
How to make sure Matlab finds yourm-file
� Change current directory using the cd command orby clicking in the Directory panel
� Select the ’Set Path’ option in the File menu
� Type one of the following commands in thecommand window:
addpath C:\Program\Matlab6k5\myfiles
path(path,’C:\Program\Matlab6k5\myfiles’)
Day 1 – p.20/??
The added path will not be found by Matlab the next timeyou start the program. In order to make permanentchanges to Matlab’s search path you can
� Type path2rc after the addpath command
� Type the path in the file called ’pathdef.m’
� Write the addpath command in the file ’startup.m’(this file is run every time Matlab starts up)
� Modify the environment variable MATLABPATH
Day 1 – p.21/??
Example
myfun.m
function y = myfun(t)
y = t * sin(t);
Day 1 – p.22/??
What is a function
� A function is an m-file beginning with the word’function’
� A function has a user-specified input and output
� A function has its own ’local’ workspace. Variablesdefined in the function are not stored in the ordinaryworkspace. Nor are your workspace variablesaltered if given a new value in the ’local’ workspace.A function does not assign any values to anything
� Exception to this rule is if you define a globalvariable. Type ’help global’ for more information
� You can have several functions stored in one file.The ’subfunctions’ work exactly as a normal function,but can not be axcessed directly from the commandwindow (unlike other languages). Day 1 – p.23/??
Example
spir.m
function [x,y] = spir(t)x = cos(20*t).*exp(-t.ˆ2);y = sin(20*t).*exp(-t.ˆ2);
spirplot.m
function [x,y] = spirplot(t)x = cos(20*t).*exp(-t.ˆ2);y = sin(20*t).*exp(-t.ˆ2);plot(x,y)
Day 1 – p.24/??
Example
spir3.mfunction [x,y,z] = spir3(t)
x = cos(20*t).*exp(-t.ˆ2);y = sin(20*t).*exp(-t.ˆ2);z = exp(-t.ˆ2);plot3(x,y,z)
Day 1 – p.25/??
Loops
A for-loop assigns a number of different values to aparameter, then stops performing the task. Begins withthe word ’for’, ends with the word ’end’.for n = 1:N
a(n) = 1/n;end
You can write the loops directly in the command window:
>> for n = 1:N, t(n) = 1/n; end>> for r = linspace(0,1,20), q = sin(r); end>> for a = A, plot(a), end
Commas separate several commands on a line. If
�
is a
matrix the loop variable becomes a vector of the separate
columns in ADay 1 – p.26/??
Example
forloop2.mclear % Clears the workspace
A = peaks; % A is the test-matrix% peaks
for a = Aplot(a) % a obtains the value of
% each column in Adrawnow % Updates the figure window
% immediatelyend
Day 1 – p.27/??
Example
ApBloop.m
A = ones(1000,1000); % Creates matrices A and BB = zeros(1000,1000);C = zeros(1000,1000);
tic, % Starts the stop-watchfor n = 1:1000 % Start of the first for-loop
for m = 1:1000 % Start of the second for -loopC(n,m) = A(n,m)+B(n,m);
end % Ends the second loopend % Ends the second looptoc
tic, C = A+B; toc
The computation is approximately 15 times faster without
the loop!
Day 1 – p.28/??
Example
resizeloop.m
A = ones(500,500); % Creates matrices A, B and CB = zeros(500,500);
tic, C = A+B; toc
tic, % Starts the stop-watchfor n = 1:500 % Start of the first for-loop
for m = 1:500 % Start of the second for -loopC(n,m) = A(n,m)+B(n,m);
end % Ends the first loopend % Ends the second looptoc
The computation is 400 times faster without the loop!
Avoid loops and never resize matrices inside the loops.
Day 1 – p.29/??
Loops
A while-loop performs a task until a logical test provesfalse. Begins with the word ’while’, ends with the word’end’
while t < tmax,a = sin(t);t = t + dt;
end
Day 1 – p.30/??
Example
whileloops.mclear % Clears the workspace
t = 0; % Initial value of ttmax = 10; % End value of t
while t < tmax % Starts the while-loopa = sin(t);t = t + dt; % Increments t
end % Ends the while-loop
a = 1;while a > 0.1 % Starts the while-loop
a = rand; % calculates aend % Ends the while-loop
Day 1 – p.31/??
Emergency exit
If you want to interrupt a loop while it is running, type
Ctrl+C. If you are working on a remote computer, try giv-
ing the Ctrl+C command in the window that controls the re-
mote access (e. g. the xterm-window) rather than in the
Matlab command window.
Day 1 – p.32/??
Logical tests
Logical operators perform a test and returns 0 if the testproved false and 1 if it proved true. Standard logical testsare:
�
== equal
�
˜= not equal
�
> larger than
�
< smaller than
�
>= larger than or equal
�
<= smaller than or equal
Logical expressions may also be combined using:
�
| or
�
& and
Day 1 – p.33/??
Example
whiletest.m
while ((a > 0.1) & (a < 0.9))a = rand;n = n+1;
end
Day 1 – p.34/??
Branch statements
Performs a task if a logical test prove true and skips thetask if it prove false. Begins with the word ’if’, ends withthe word ’end’.For example, the statement:
� � � � � �� � � � � � � � � � � (5)
is written in Matlab code as
if a == 0 | a > 2b = 1;
end
Day 1 – p.35/??
Logical matrix
When logical tests are performed on a matrix, a logicalmatrix is returned. A scalar can be compared to anymatrix, but two matrices can only be compared if they arethe same size. There are special matrix-tests that returna single value, for example the function isequal thatreturns 1 if the two matrices are of the same size and allelements are equal.Example (logmat.m):A = [1 0 3; -2 3 0];B = [2 -3 4; 2 1 -0.1];
A > B
returns
ans =0 1 00 1 1
Day 1 – p.36/??
Work smarter!
� Save time
� Save CPU time
� May become an issue if your program works!Tempting to increase domain or decrease gridsize and time step
Day 1 – p.37/??
Save time
� Use Matlab!
� Document your scripts and functions: Addcomments and help.If the first lines in an m-file are commented, these willbe displayed in the command window when you typehelp filename
� Indents makes it easier to read the program
� Include error possibilities in your functions andscripts:error(’error message’)stops the execution and displays the error messagein the command window.
Day 1 – p.38/??
Save time
� Start scripts with ’clear’
� Think about what is best, function or script
� Functions may be slower CPU-wise but still savetime if used often
� The good thing with functions is that they do notassign any values to anything
� Try to divide your problems into smaller parts. Forexample it might be useful to have separate scriptsfor visualising your result
Day 1 – p.39/??
Save time
� Have a system when you name your variables
� Matrix: Capital letters
� Natural numbers: m, n, p, q
� Global variables: long names with capital letters
� If you get stuck, try the debug option
� Read the manual (or visit helpdesk) sometimes
� Visit the web and user-groups
Day 1 – p.40/??
Save CPU-time
� Do not resize matrices in loops - define the matrixbefore the loop (same as prealloc memory).
Resizeloop2.m
tic,A(5e4) = 0; % Presizes Afor n = 1:5e4,
A(n) = sin(n)*n; % Computes sin(n)*n without% resizing the matrix
end,toc
clear % Clear the workspace
tic,for n = 1:5e4
A(n) = sin(n)*n; % Computes sin(n)*n and resizes% the matrix A each step
endtoc
Day 1 – p.41/??
� Use matrices rather than loops whenever possible.Include matrix arguments in your functions.
vectorize.m
% Compares the computational speed of% vectorized code and a for-loop
clear
tic,A = sin(1:1e6).*[1:1e6]; % Vectorized codetoc
tic,for n = 1:1e6
A(n) = sin(n)*n; % For-loopendtoc
� The difference is not always so great!Day 1 – p.42/??
� User defined functions usually take a little longerthan built-in functions ....
userfun1.m
% Compares the computational speed of when a% user-defined function is called
x = linspace(0,10,1e6);tic, A = f(x);toc % user-defined function
tic,A = exp(-x.ˆ2).*sin(x).*x; % Built-in functionstoc
f.m
function y = f(x)y = exp(-x.ˆ2).*sin(x).*x;
Day 1 – p.43/??
� ......but can take a LOT longer:
userfun2.m
clear
A(1e5) = 0; % Presizes A
tic,for n = 1:1e5
% Built-in functionsA(n) = exp(-n.ˆ2).*sin(n).*n;
endtoc
tic,for n = 1:1e5
A(n) = f(n); % User -defined functionendtoc
Day 1 – p.44/??
What slows down the program?
The new, fast Matlab (comparable in speed to Fortran)has accelerated loops that computes almost as fast asvectorized code. However, the accelerated loops onlywork with built -in functions. Furthermore, it does notwork for all datatypes. Although a ll common datatypesare included it is important that there is no confusion overwhich datatype is used. For example, 2*i is notaccelerated but 2i is.
If accelerated code is ’interrupted’ by an unaccelerated
command, the rest of that line executes as ’slow’ code
(Matlab 5 speed).
Day 1 – p.45/??
acctest.m
clearA = rand(500,500);B = zeros(500,500);ticMe.name = ’Anna’; % Breaks the accelerated
% code (structure)for n = 1:500 % Start of the first for-loop
for m = 1:500 % Start of the second for-loopB(n,m) = sin(A(n,m))*cos(A(n,m));
end % Ends the second loopend % Ends the second looptoc
tic,Me.name = ’Anna’; for n = 1:500, for m = 1:500, B(n,m) = sin(A(n,m))*cos(A(n,m)); end, end, toc
Try not to write many commands in one line!
Day 1 – p.46/??
Summary Day 1
Matlab is extremely easy to use. It is a perfekt tool for’checking out’ different problems when you need a quick,easy way to visualise them.The big drawback with Matlab has always been thecomputation speed. The new Matlab is comparable inspeed to Fortran and C/C++ but only if you use it rigtht. It iseasy to slow down the program!
For applications when you need to define other classes
than matrixes Matlab is both slow and difficult.
Day 1 – p.47/??
Day 2
Day 2 – p.48/??
Importing and exporting data
� Matlab supports most (all?) common data formats.For example binary, ascii, CDF, Excel worksheet aswell as Matlabs ’own’ type mat-file (binary). A list ofall compatible types is given as hand-out.
Day 2 – p.49/??
Importing and exporting data
There are two ways of importing and exporting data inMatlab.
� Import wizard
� Interface that guides you through the importprocedure, and automatically choses the rightoptions for the specific (formatted) data type.
� Possibility to preview and make initialadjustments of the data. Export data as .mat
� Commands
� This way is quicker if you e. g. are importingseveral files of similar type, or are used to doingit ’the old way’
� If you want to export data in different formats youmust type! Day 2 – p.50/??
Demonstration
� Import wizard
Day 2 – p.51/??
Typing import commands
� Mat-files (Matlabs own binary storage file)
load filename save filename
load filename A B save filename A B
� Ascii-files
load -ascii filename A Bsave -ascii filename A B
try1.m: load -ascii VIK_1990.dat
� Number of columns in ascii file must be equal for allrows
Day 2 – p.52/??
Typing import commands
� Delimited text files
A = dlmread(’filename’,’delimiter’)Reads the file ’filename’ into the variable Adelimiter:
Can be anything, e. g.’ ’ = space delimited’\t’ = tab delimited
try2.m: A = dlmread(’VIK_1990.dat’,’ ’)
Day 2 – p.53/??
Typing import commands
A = dlmread(’filename’,’delimiter’,RANGE)
Reads a portion of the file ’filename’ into the variable A.RANGE = [Rstart Cstart Rend Cend] specifies the row Rand column C where to start and end reading. It can benoted that R and C start at zero, i. e. Cstart = 0 indicatesthe first column and so on.
� dlmread fills empty places in the data with zeros
� dlmwrite(’filename’,Var,’delimiter’)Writes the variable Var into the file ’filname’ using thespecified delimiter
try3.m: A = dlmread(’VIK_1990.dat’,’ ’,[1 0 8760 4]);
Day 2 – p.54/??
Typing import commands
� Binary files
fid = fopen(’filename’,’permission’)A = fread(fid,size,precision)
Reads the data in file ’filename’ into the variable A
fid = fopen(’filename’,’permission’)fwrite(fid,A,precision)
Writes the variable A with the desired precision into thefile ’filename’. The data is written in column order.
help iofun
More information about import/export of data
Day 2 – p.55/??
Typing import commands
binwrite.m
% writes the data stored in Data to the bi-nary file VIK_yrs.bin
fid = fopen(’VIK_yrs.bin’,’wb’) % open filefwrite(fid,[Time,Sealv1]’,’float’); % write data to file
% transpose% before write
fclose(fid); % close filefigure(1), plot(Time,Sealv1) % plots datatitle(’Data before writing to binary file’)
Day 2 – p.56/??
Typing import commands
� Binary files
binread.m
clear
fid = fopen(’VIK_yrs.bin’,’rb’); % open fileData = fread(fid,[2 inf], ’float’); % read in dataTime = Data(1,:)’; % tarnspose data
% to columnsSealv1 = Data(2,:)’;fclose(fid); % close file
figure(2), plot(Time,Sealv1) % plots datatitle(’Data after reading from binary file’)
Day 2 – p.57/??
Data treatment.
Matlab has a wide range of different functions forstatistical and time-series analyses of data. Here only afew will be demonstrated. The purpose is to teach theprinciple, instructions for use of more functions can befound with the built-in help.
� Time-series analyses
� Curve fitting
� Interpolation
� Statistics
Day 2 – p.58/??
Fourier transforms
Matlab uses the complex discrete Fourier transform
��� �� �
,
� � � � � �
����
� � � � � ��� � � � � �� � � �� � � � � �� (6)
where � is an equally spaced data set of
�
points. Aspectrum of a time series may be obtained from theabsolute value of the discrete Fourier transform. Toobtain the Fourier transform, use the function fft (one-dimensional), fft2 (two-dimensional) or fftn(n-dimensional). To obtain the inverse, use ifft(one-dimensional), ifft2 (two-dimensional) or ifftn (n-dimensional).
ExampleDay 2 – p.59/??
spectrum.m
clear
readfiles
FT = fft(Sealv1);spkt = abs(FT).ˆ2;loglog([1:length(spkt)]./length(spkt),spkt), xla-bel(’Frequency (h-1)’)
Day 2 – p.60/??
Curve fitting
� Fitting data to polynomial
A dataset may be fitted into a polynomial of degree N byuse of the function polyfit. The error is minimized in aleast square-sense.A = polyfit(y,x,N)returns the coefficients of the polynomial ���
� � �
defined as
� �� � � � � � �� � � �� � ��� � ��� � � � �� �
� � �� � � �� (7)
Where
� � � � �� � �� � � � � � � �� � �� � �� �
Day 2 – p.61/??
cfit1.m
clear % clear the workspaceA = dlmread(’VIK_1990.dat’,’ ’,[1 0 8760 4]);
y = A(:,5); % the datax = [1:length(y)]’;
a = polyfit(x,y,1);yfit = polyval(a,x);
close(gcf)plot(x,y,’b’,x,yfit,’x’)
Day 2 – p.62/??
cfit2.m
clear % clear the workspaceA = dlmread(’VIK_1990.dat’,’ ’,[1 0 8760 4]);
y = A(:,5); % the datax = [1:length(y)]’;
a = polyfit(x,y,1);yfit = polyval(a,x);
a = polyfit(x,y,2);yfit2 = polyval(a,x);
a = polyfit(x,y,7);yfit7 = polyval(a,x);
plot(x,y,’b’,x,yfit1,’x’,x,yfit2,’g’,x,yfit7,’k’)
Day 2 – p.63/??
Curve fitting
� Curve fitting with arbitrary functions
The ability to solve over-determined equation systemscan be used to fit a data set into a linear combination ofarbitrary functions. Instead of the polynomial in previousexample, use a sum of arbitrary functions
� �� � � � �� �� � � � � �� �� � � � � � � � � � � � � � � �
(8)
The coefficients � �are to be determined so that the error is
minimized.
Day 2 – p.64/??
Curve fitting
� Curve fitting with arbitrary functions
By computing the function values at each data point anover-determined equation system is obtained,
�� � �,
where
� ��
������� � �� � �� � �� �
� � �
� � � �� �
�� � �� � �� � �� �
� � �
� � � �� �
� � � � � � � � � � � �
�� � � �� �� � � ��
� � �
� � � � ��
��
� ��
�������
��� � �
� ��
�� �
������
����
� �� �
(9)
Day 2 – p.65/??
Interpolation
Matlab has built-in functions for interpolating sampled data
in N dimensions. The sampling points must be sorted in
ascending order(2 dimensions or higher), but may be irreg-
ularly spaced. Linear interpolation is performed by default,
but other methods can be used by specifying a ’method’ in-
put in the interp functions.
Day 2 – p.66/??
Interpolation
One-dimensional interpolation is performed by use of thefunction interp1.
� � � � � � � � � � � � � � � � � � � � � � �
takes the original data �
(measured at points �) and calculates the interpolatedvalues
� at the chosen new coordinates
� . The default(linear) interpolation is used.
intp.m
x = 0:8; y = sin(x);
xi = linspace(0,8,100);
yiL = interp(x,y,xi);yiC = interp(x,y,xi,’spline’);
plot(x,y,’.’,xi,yiL,yiC), legend(’Data’,’Linear in-terp’,’Spline interp’)
Day 2 – p.67/??
Interpolation
Two-dimensional interpolation is performed by use of thefunction interp2.
� � � � � � � � � � � � � � � � � � �
(10)
takes the original data � (measured at points � � �) and cal-
culates the interpolated values
� at the chosen new co-
ordinates
� � � . The default (linear) interpolation is used.
� can be a row vector and
� a column vector defining the
new grid.
Day 2 – p.68/??
Interpolation
� � � � � � � � � � � � � � � � � � � �� � � � � � �
(11)
Uses cubic spline interpolation rather than the defaultlinear.
� � � � � � � � � � � � �
(12)
expands � by
�
interpolates between every element, work-
ing recursively. The data are assumed to be equally
spaced in the x- and y-directions.
Day 2 – p.69/??
Intp2D.m
clear
x = -2:2;y = [-2:2]’;z = (sin(y).*exp(-y.ˆ))*(sin(x).*exp(-xˆ2));
xi = linspace(-2,2,100);yi = linspace(-2,2,100)’;
ziL = interp2(x,y,z,xi,yi);
subplot(121), mesh(xi,yi,ziL)title(’Linear interpolation’)
ziC = interp2(x,y,z,xi,yi,’splnin’);subplot(1,2,2), mesh(xi,yi,ziC)title(’Cubic spline interpolation)
Day 2 – p.70/??
Interpolation
Three-dimensional interpolation is performed by use ofthe function interp3.
� � � � � � � � � � � � � � � � � � � � � � �
(13)
takes the original data � (measured at points � � � � �) and
calculates the interpolated values
� at the chosen new
coordinates
� � � � � . The new grid
� � � � � can be ei-
ther three-dimensional matrices or vectors (in which case
� must be a column vector).
Day 2 – p.71/??
Interpolation
� � � � � � � � � � � � � � � � � � � � � � � � � � � � � �
(14)
Uses interpolation method specified in ’method’ (seehand-out) rather than the default linear.
� � � � � � � � � � � � �
(15)
expands � by
�
interpolates between every element,working recursively. The data are assumed to be equallyspaced in the x-, y- and z-directions.
� � � � � � � � � �� � �� � �� � � � � � � � � � � � � � � � � � � � �
�
(16)
N-dimensional interpolation
Day 2 – p.72/??
Irregular data sets
For one dimensional data sets the data can be sortedbefore the interpolation is performed
�� � � �� � � � �
(17)
sorts the elements in vector � in ascending order andstores them in the vector
��.
� �� � � � � � �� � � � �
(18)
sorts the elements and also stores the indices in vector
�
.
Day 2 – p.73/??
Irregular data sets
� �� � � � � � �� � � � �
(19)
�� � � � � �
(20)
uses the stored indices to rearrange the correspondingy-values. In the above example, the data � that were
sampled at (irregular) points � have been rearranged in the
vector
�� sampled at (ascending) points
��.
Day 2 – p.74/??
Irregular data sets
For data sets in two or more dimensions it is morecomplicated to sort the sample points so that they areascending in every dimension. The sorting may need tobe done several times.For two-dimensional irregularly sampled data sets thefunction griddata may be used instead.
� � � � � � � � � � � � � � � � � � � � � � � � � � � � �
(21)
� � � � � � � � � � � � � � � � � � � � � � � � � � �
� � � � � � �
(22)
� � � � � � � � �
(23)
Day 2 – p.75/??
irrdata.m
x = 4*rand(1,8)-2;y = 4*rand(8,1)-2;z = (sin(y).*exp(-yˆ2))*(sin(x).*exp(-xˆ2));
xi = linspace(-2,2,100);yi = linspace(-2,2,100)’;
ziL = interp2(x,y,z,xi,yi);
subplot(121), mesh(xi,yi,ziL)title(’Linear interpolation’)
ziC = interp2(x,y,z,xi,yi,’spline’);subplot(1,2,2), mesh(xi,yi,ziC)title(’Cubic spline interpolation)
Day 2 – p.76/??
irrdata2.m
x = 4*rand(1,8)-2;y = 4*rand(8,1)-2;z = (sin(y).*exp(-yˆ2))*(sin(x).*exp(-xˆ2));
xi = linspace(-2,2,100);yi = linspace(-2,2,100)’;
ziL = griddata(x,y,z,xi,yi);
subplot(121), mesh(xi,yi,ziL)title(’Linear interpolation’)
ziC = griddata(x,y,z,xi,yi);subplot(1,2,2), mesh(xi,yi,ziC)title(’Matlab 4 interpolation)
Day 2 – p.77/??
Irregular data set
� � � � � � � � � � � � � � � � � � � � � � � �
(24)
interpolates the data � measured at (irregularly spaced)points � � �. The new grid specified by
� � � � �
can be a row-and column vector. By default, linear interpolation isperformed.
� � � � � � � � � � � � � � � � � � � � � � � ��
� � � � � � �
(25)
Uses the chosen interpolation method.
Day 2 – p.78/??
Statistics
Matlab has a special statistics toolbox with a number offunctions (type ’ help stats’ for complete list). There arealso several statistical functions included in the regularMatlab library (see handout).
Some statistical functions return a scalar number when ap-
plied to a vector. If applied to a matrix, a row vector con-
taining the results from each of the columns is instead re-
turned.
Day 2 – p.79/??
stat1.m
clearclf
Level(8760,12) = 0; % presizes the matrix
for n = 1:12filenum = num2str(1989+n); % convert year to
% stringfilename = [’VIK_’,filenum,’.dat’]; % Append year to
% filenameA = dlmread(filename,’ ’,[1 0 8760 4]); % read the file
Level(:,n) = A(:,5);end
stdev = std(Level);plot(stdev)
Day 2 – p.80/??
Statistics
Sometimes missing data points in a series are replaced
with NaN. No statistical functions will work on these sets,
since an operation involving NaN will always return NaN.
Try removing all points with NaN (use e.g. the isnan func-
tion) or use the special functions that are defined for such
series, for example nanmax, nanmean etc).
Day 2 – p.81/??
Calculus and equation solving
We are now going to try different methods of integration,
derivation and root finding in Matlab. Besides the imme-
diate use of methods, the purpose is also to demonstrate
some of the programming tools and how to make the most
efficient use of Matlab (optimization).
Day 2 – p.82/??
Analytical methods.
All common operations can be done on analytical objects,including factorization, derivation and integration.Matlabs analytical toolbox is built on Maple, and usesMaples commands etc. An symbolic object is defined inMatlab by use of the command ’sym’ or ’syms’.x = sym(’x’)
syms x y z
Day 2 – p.83/??
demoan.m
clear
syms x y % defines x and y% as symbolic objects
f = cos(x)ˆ2 + xˆ3 % defines f(x)subplot(211), ezplot(f) % plots f(x) in top half
q = exp(-xˆ2-yˆ2)*sin(x*y) % defines g(x)subplot(212), ezsurf(g) % draws the surface in
% lower half
Day 2 – p.84/??
Analytical integration
The function ’int’ integrates a function analytically. If noanalytical integral can be found, the input is returned.Usage:h = int(f)integrates the equation f with respect to thedependent variable
h = int(f,y)integrates the equation f with respect to y
example anin.m
Day 2 – p.85/??
Analytical derivation
The function ’diff’ calculates the derivative of a functionanalytically.Usage:g = diff(f)g = diff(f,y) Takes the derivative with respect to y
Example ande.m
Day 2 – p.86/??
Analytical root-finding
The function ’solve’ is used to find the root to the equation
� � � � � �
.Usage:a = solve(f) Solves f(x) = 0a = solve(’f(x)=3’) Solves f(x) = 3
Example anro.m
Day 2 – p.87/??
Numerical integration and derivation
Matlab has a number of built-in functions for numerical
derivation and integration. The good thing with these is
that they are accelerated and execute faster. The bad thing
is that the code can not readily be viewed. In addition to
the built-in functions there are several ordinary m-files for
derivation and integration included in the Matlab library. A
list of built-in and library files is given as hand-out.
Day 2 – p.88/??
The integral of a data set
Suppose we have sampled a signal
� � � �
at a time intervalof
� �
. A crude estimate of the time integral of the data setis then given by
��
� � � � � � ��
����
� � � � � �
(26)
There are different ways to perform the above summation
in Matlab.
Day 2 – p.89/??
Method
1. For-loop
int = dt*A(1)for n = 2:N
int = dt*A(n) + int;end
2. Sum-function
int = dt*A(1)*sum(A);
3. Trapezoidal estimate
int = trapz(A);int = trapz(t,A)
Example numint.m
Day 2 – p.90/??
Primitive function
1. By for-loop:
int(N) = 0;
for n = 1:Nint(n ) int(n-1)’dt*A(n);
end
2. Using cumsum:
int = dt*cumsum(A);
3. Trapezoidal estimate:
int = dt*cumtrapz(A);int = cumtrapz(t,A);
Related functions: prod(A), cumprod(A)
Example: numpr.m
Day 2 – p.91/??
Better methods
The following methods integrates an analytical function(cn not be applied for a dataset).
int = quad(’fun’,a,b) Adaptive Simpson quadrature
int = quadl(’fun’,a,b) Adaptive lobatto quadrature
the function to be integrated is defined in the function file’fun’ (can be user-defined). The integral is calculatedfrom a to b.
Example: numpr2.m
Day 2 – p.92/??
Numerical estimate of the derivative
An estimate of the time derivative of dataset� � � �
sampledat time interval
� �
is
� � � � � �
� � � � � � �
�
� � � �
� � (27)
The differentiation can be done with different methods inMatlab.1. For-loop:for n = 1:N
der(n) = (A(n+1) - A(n))/dt;endremember to presize der
2. Vector:der = (A(2:N) - A(1:N-1))/dt;
3. Built-in functionder = diff(A)/dt;
Day 2 – p.93/??
The function ’diff’
diff(A,M) Performs the differencing M times recursivelydiff(B), where
�
is a matrix performs the differentiationalong each row
diff(C), where C an M-dimensional matrix performs the dif-
ferntiation along the first non-singleton dimension
Day 2 – p.94/??
More dimensions
Gradient
� � �� �
� �� � �
� �� �
� � �� �
� �� � ��� � � �
� �� �
� � (28)
The gradient of a scalar field in N dimensions iscalculated with the function gradient, which is simply diffapplied along each of the dimensions.
� �� � ���
� � � � � � � � � � � �
Two dimensions
� �� � ��� � ���
� � � � � � � � � � � �
Three dimensions
� �� � ��� � ��� � � � � � � � � � � � � � � � � � � �
N dimensions
Example graddemo.m
Day 2 – p.95/??
More dimensions
LaPlace operatorThe curvature of a scalar field in N dimensions iscalculated with the function del2, that uses a centeredfinite difference scheme in N dimensions.
� �� �� ��
� ��
�� ��
� ��
�� ��
� ��
� � � � �� ��
� �� (29)
L = del2(A) Calculates the LaPlacian in N dimensions
L = del2(A,X,Y,Z,. . . ,N) Uses the grid spacing defined by
(X,Y,Z,...,N)
Day 2 – p.96/??
Numerical root-finding
The Matlab functions for numerical root finding requiresan initial guess of the root. If the initial guess has to beperformed by computer a logical test can be used. Thelogical operator any returns true if at least one element ofa logical matrix is true. A related logical operator is all,which is ’true’ only if all elements of the matrix are true.
if any(sign(fx(1:N-1))˜=sign(fx(2:N)));n0 = find(sign(fx(1:N-1))˜=sign(fx(2:N)));x0 = x(n0);
elseerror(’No initial guess could be found’);
end
Day 2 – p.97/??
Afternoon exercise
A similar test can be done in two or more dimensions.The option of sign-change in the other directions has tobe included, and the initial guess will be in the form of amatrix (several indices will be returned).I = find(A) where A is a logical matrix of N dimensions,returns a row matrix I. To convert I to array indices (if Ahas two or more dimensions) use the function ind2sub.
[I,J,K,L,. . . ] = ind2sub(size(A),I)
Day 2 – p.98/??
Matlab functions for root-finding
The functions fzero (one dimension) and fsolve (Ndimensions) uses different numerical methods to find theroots of equation f(x) = 0.Usage:fzero(’f’,x0) Finds the root of the function f(x) (can beuser-defined) using the initial guess x0.
fsolve(’f’,X0) Finds the root X (N-dimensional matrix) to
the function f(x) using the initial guess X0.
Day 2 – p.99/??
Related functions
fminbind Finds an absolute minimum to a function in Ndimensions
fminsearch Finds a local minimum to a function in N dimen-
sions
Day 2 – p.100/??
Logical tests with NaN
A logical test performed on NaN is always false! All thefollowing statements are false:NaN == NaN
-Inf < NaN
-Inf > NaN
On the other hand, ’not-equal’ is always true:NaN ˜= NaN
0 ˜= NaN
If there is a risk that your operations can return NaN thefunction isnan can be used instead.
isnan(NaN) returns true.
Day 2 – p.101/??
Ordinary differential equations
Analytical solutions can be attempted with the functiondsolve.Usage:y = dsolve(’Equation’, ’BC1’, ’BC2’,....,’variable’)
S = dsolve(’Equation1’, ’Equation2’, ’BC1’,....)
Example odean.m
Day 2 – p.102/??
Ordinary differential equations
A number of different ODE solvers are available in Matlabs
library. The different solvers are designed for various types
of ODEs (stiff or non-stiff etc) and different levels of accu-
racy. A complete list of the solvers can be found by typ-
ing ’help ode23’. The usage is equivalent and will here be
demonstrated with the solver ODE23 (a solver for non-stiff
ODEs, low order method).
Day 2 – p.103/??
Manual for use of ODE23
The solution � at times
�
to the ODE is obtained by[t, y] = ode23(odefun,tspan,y0)
where odefun is a function file that describes the ODE.The time span is tspan = [t0 tend] and initial conditionsare y0 = y(t0). The file odefun should return the timederivative given the input
�
and �, i. e.
� �� �
� � � � � � � � � � �
(30)
Day 2 – p.104/??
Manual for use of ODE23
If a system of differential equations is going to be solvedthen odefun should have the form
� �� � �
��
� � �� �
� � � � � � � � � � � � � �� �� � � � � � � �
� �
(31)
To solve higher-order differential equations, convert to a
system of first-order equations.
Day 2 – p.105/??
Example: Bessel’s equation of zerothorder
Bessel’s equation can be converted to the following set offirst-order differential equations:
��
� � �
� �
� ��
� � �
� �
� � � �
(32)
� � � � �
� �
� �� � �
(33)
Day 2 – p.106/??
bess.m
function dydt = bess(t,y)g = y(1);f = y(2);dgdt = -g/t-f;dfdt = g;
dydt = [dgdt; dfdt];
Day 2 – p.107/??
odedemo.m
clearclf % clears the figure window
[t23,y23] = oded23(’bess’,[eps,10],[0;1]);% The function can not handle t = 0bess23 = y23(:,2);
[t45,y45] = ode45(’bess’,[eps,10],[0;1]);% use t = eps insteadbess45 = y45(:,2);
t = linspace(0,10,1000);plot(t,besselj(0,t),’b’,t23,bess23,’r’,t45,bess45,’g’)legend(’Analytical’,’ODE23’,’ODE45’)
Day 2 – p.108/??
Curve fitting with arbitrary functions Solution to exercise 2b: Find the least-square fit of a data set to a linear combination of sin(t), sin(2t) and sin(3t). Set )3sin()2sin()sin()( 321 tatatatyF ++= . From the data set we have
)3sin()2sin()sin(.....
)3sin()2sin()sin()3sin()2sin()sin(
)3sin()2sin()sin(
200320022001200
3332313
2322212
1312111
tatatay
tatataytatatay
tatatay
++=
++=++=
++=
or y = F*a (1)
where
=
200
3
2
1
yyyy
y
=
)3sin()3sin(
)2sin()2sin(
)sin()sin(
)3sin()2sin()sin()3sin()2sin()sin(
200
3
200
3
200
3
222
111
tt
tt
tt
tttttt
F,
=
3
2
1
ccc
a
We can not solve for a exactly (the system is overdetermined), but a least-square fit of eq. (1) can be found by left-division of y with F: a = F\y. Note that there is no warning message displayed!
The Matlab code looks like this: t = xydata(1,:)'; y = xydata(2,:)'; F = [sin(t), sin(2*t), sin(3*t)]; a = F\y; yfit = a(1)*sin(t) + a(2)*sin(2*t) + a(3)*sin(3*t);
Partial differential equations
In order to illustrate two techniques for PDE solving thediffusion (or heat) equation will be used:
� �� �
� � � � �(34)
For constant � an initial distribution
� � � � � �� ���� � �
�
spreads in all directions according to
� � � � �� �
��� � � �
���� � �
� �� � � � (35)
where
� �
� �� � �� � �� �
� � � is the distance to the origin.
Day 2 – p.109/??
Explicit numerical scheme The field T at time t + ∆t is approximately given by
Tt
tTttT 2)()(∇≈
∆−∆+
κ , or
TttTttT 2)()( ∇∆+=∆+ κ . The function del2 calculates the LaPlacian:
del2(T) T2
41 ∇ 1 or 2 dimensions
del2(T) T2
61
∇ 3 dimensions
del2(T) TT
2
)dim(*21
∇ N dimensions
Explicit scheme The Matlab code for the explicit scheme looks like this: T = T + dt*K*del2(T)*2*ndims(T); ndims(T) Number of (non-singleton) dimensions del2(T,dx,dy,dz,...) Grid spacing dx, dy etc del2(T,Xv,Yv,Zv,...) Grid defined by vectors Xp, Yp etc del2(T,Xm,Ym,Zm,...) Grid defined by matrices Xp, Yp etc Example: explic3.m
Implicit numerical scheme
In an implicit scheme the space de rivative is calculatedat time
� � � �
. The temperature at this time is then thesolution to the linear equation system
� � � � � � � � �� � � � � �
(37)
where
� ��
������� � � �
�� � �
�� � � � �
�� �
�
�� � � � � �
� �
�� � � � �
���
(38)
is a tridiagonal NxN matrix and
� � � � ��� �
Example: implicit1.m Day 2 – p.111/??
Implicit numerical scheme
There are several ways to solve this in Matlab. Thequickest method makes use of LU decomposition forsparse matrices,[L,U\] = lu(A);T = U\(L\T);
The time taken for this operation can be compared withthe slower Gaussian elimination,T = A\T;
or the even slower inverse matrix method,T = inv(A)*T;
Example: implicit2.m
Day 2 – p.112/??
Implicit numerical scheme
The extension to several dimensions can be done in many
ways for the implicit scheme, for example by splitting the
operator and compute each direction independently.
Day 2 – p.113/??
The PDE toolbox
The special toolbox for calculation of partial differential
equations includes a library with numerical schemes of dif-
ferent orders. There is also a set of aides for finite element
methods, with or without graphical user interface. The pro-
gram Femlab is very user-friendly and was developed from
this toolbox. For more information, go to the Partial Differ-
ential Equation Toolbox page in the Helpdesk.
Day 2 – p.114/??
Day 3
Day 3 – p.115/??
Visualizing
Today:
� Creating different types of illustrations
� Interactive editing
� Handle graphics
� Import and export of pictures
� Movies
Day 3 – p.116/??
More than one figure
To create two or more plots, type ’figure’ in the command
window. A new figure window will open. To shift between
open figures, or create new ones with a specific number,
type ’figure(n)’. The plot commands that you issue will be
performed in the current window. One figure window can
also be subdivided into several parts. The command sub-
plot(m,n,p) divides the window into � � � plotting areas and
performs the plot command in the p’th area.
Day 3 – p.117/??
Plot
One-dimensional data can be visualised with the plotcommand.
plot(t,f) plots f as a function of tplot(t,f,x,y) plots two graphs in the same windowplot(A) plots each column of A versus
their indexplot(t,f,’g:’,x,y,’rx’) changes the linetype and color
Type ’help plot’ for a complete list of availablelinetypes.
Example: plotex1.m
Day 3 – p.118/??
Surf
A matrix can be visualized as a surface with thecommand surf.surf(z) Draws the surface z
versus the row- andcolumn indices
surf(x,y,z) Draws the surface versus x and ysurf(x,y,z,C) Uses the color map specified in C
Example: surfex1.m
Day 3 – p.119/??
Contour
Another way to visualize a matrix is by drawing a contourplot.contour(z) Draws a contour plot
versus the row andcolumn index
contour(x, y,z) Contour plot versus x and ycontour(z,N) Draws N evenly spaced contour
linescontour(z,[z0, z1, z2, ...,zN])
Draws the contour linesz0, z1, z2 etc
contour(x,y,z,[z0 z0]) Draws a single contourline, z = z0.
To create a filled contourplot, use the functioncontourf.
Example: contex1.m
Day 3 – p.120/??
Slice
One way to visualize three-dimensional data is bydrawing several (filled) contour plots in different planes.This is done by the function slice:
slice(x,y,z,V,Xp,Yp,Zp) draws contour plots of V in theplanes x = Xp, y = Yp and z = Zp.Several planes can be used.
slice(V,Np,Mp,Qp) draws contour plots of V versusits index.
Example: sliceex.m
Day 3 – p.121/??
Patch
A three-dimensional data set can also be visualised bydrawing one of the isosurfaces. The function patchdisplays an isosurface. In order to find the surface thefunction isosurface can be used. The values at the edgesof the isosurface can be found by the function isocaps.
isosurface(X,Y,Z,T,T0) finds the isosurface T = T0isocaps(X,Y,Z,T,T0) finds the values of T at the
edge of the isosurfacepatch(surface,’property’,value);
draws the surface
Example: patchex.m
Day 3 – p.122/??
Demonstration: Interactive editing offigures
Day 3 – p.123/??
Interactive editing of figures
The changes that were made interactively can also bedone with written commands. There are two ways to dothis.
� Include the properties in the plot command
� Create a ’handle’ when the plot is drawn. The handlecan be used later on to change the plot properties.
Day 3 – p.124/??
Setting properties with the plotcommand
All the parameters that can be edited from the plotwindow can also be adjusted directly when the plot isdrawn. This is done by including additional stringarguments in the plot command.
plot(x,y,’LineWidth’,2,’Color’,[0 0 1],’LineStyle’,’--’)
A color is specified by three numbers corresponding tothe RGB color values.
surf(x,y,z,’LineStyle’,’none’,’FaceColor’,’interp’)
Day 3 – p.125/??
Examples
plotex2.msurfex2.mcontex2.m
produces plots with the same editions that were previously
made interactively.
Day 3 – p.126/??
Example
If we want to remove the lines in a filled contour plot bytyping
contourf(x,y,z,’LineStyle’,’none’)
it does not work. This is an example of when it is good touse handle graphics.Example: contex3.m
Day 3 – p.127/??
What is a handle?
A handle is simply a number. Its purpose is to help Matlab
keep track of the different plots, axes, figure windows etc
(’objects’). In the manual some of the handles are called
’parents’ and ’children’. This is a way to rank the different
objects - a figure window can not be created unless there is
a screen to create it in. The screen is then called the ’par-
ent’ to the figure and the screen handle is parent to the fig-
ure handle.
Day 3 – p.128/??
Get hold of a handle
To find a handle, simply write a parameter name in frontof your plot command.Hl_xy = plot(x,y);
A handle called ’Hl_xy’ has been created. The handleidentifies the plot.
Hf_fig = figure(1)
A handle called ’Hf_fig’ identifying the figure window has
been created.
Day 3 – p.129/??
Get hold of a handle
Ha_ax = axes
This way the handle to the object ’axes’ is created (not tobe confused with the command axis!). Axes is animportant object that is parent to all surfaces, lines etc inthe plot. The handle to the current axes object can alsobe obtained with the function gca.Ha_ax = gca
Day 3 – p.130/??
Use the handle
With the handle it is eas y to make changes to the plot.The function ’set’ changes the handle properties:
set(Hl_xy,’LineStyle’,’:’)set(Hl_xy,’LineWidth’,4,’Color’,[0 1 0])
The function ’get’ can be used to obtain a list of all thehandle properties.get(Hl_xy)
displays a complete list of the properties of the object withhandle Hl_xyExample: hangr1.m
Day 3 – p.131/??
The handle hierarchy
When handles are used to edit the plot it can be confusing
which properties belong to which object (i. e. which handle
should be used). It is then helpful to keep in mind how the
objects are related: A Figure window is parent to the axes.
The Axes object is parent to everything else that is added
in the plot (for example surfaces, lines and light-sources).
Day 3 – p.132/??
Several handles
One plot command can create several objects. In thiscase a column vector of all the handles are created:Hl_peaks = plot(peaks);
returns a column matrix of 50 handles. The handleproperties can be adjusted one by one,
set(Hl_peaks(n),’LineWidth’, 2)
or all together
set(Hl_peaks,’LineWidth’, 2)
Day 3 – p.133/??
The exception that confirms the rule
The functions ’contour’ and ’contourf’ are special in thatthey have an optional function output - the coordinates ofthe calculated contours. The commandc = contour(z)
does not return a handle, but a 2*N matrix containing thecontour coordinates. To obtain the handle of the contourplot two arguments must be specified:[c, Hl_cont] = contour(z)
returns the handles of the created lines in the columnvector Hl_cont.Example: contex4.m
Day 3 – p.134/??
The handle properties
The properties of an object can also be stored. This canbe useful if a plot is edited ’by hand’ and the new settingsare to be applied to subsequent figures. The commandProp_H = get(Hl_cont)
stores the properties of the object in Prop_H.
Day 3 – p.135/??
Structures
The parameter Prop_H is a new type of variable - a’structure’. The values stored in it are not identified byindices (as in matrices) but by the value name. Forexample,Prop H.Colorreturns the line color value.Prop H.LineWidthreturns the line width.Example prop1.m
Day 3 – p.136/??
Using the handle
By use of the handles, it is possible to construct a graph,make changes interactively and then save the propertiesfor later use. This can be achieved by use of two scripts.Run the first script to create the object, then run thesecond script after the interactive editing has been doneto store the properties.Example 1: hangr11.m + hangr12.mExample 2: hangr21.m + hangr22.m
Day 3 – p.137/??
Using the handle
The next time you want to use the settings, the handleproperties simply has to be loaded into the workspaceand applied:
Ht_new = title(’New plot’);set(Ht_new,Oldprop)
Hs_new = surf(Newdata);set(Hs_new,Oldprop)
Example: hangr13.m, hangr23.m
Day 3 – p.138/??
List the properties
To get a list of all the ’settable’ properties of a handle, type
set(Hx_obj) lists all the properties that arepossible to modify
get(Hx_obj) displays a complete list of all theobject properties
Day 3 – p.139/??
Export and import of graphics
A plot can be exported in a number of different picture for-
mats. This can be done either from the File menu (chose
’export’) or by typing in the command window. The options
available from the File menu are not as extensive as from
the Command window.
Day 3 – p.140/??
Demonstration: Export from themenu
Day 3 – p.141/??
Typing the export command
The command ’print’ is used to export a figure fromMatlab.Usage:
� print �� � � � � � � � �
� � � � � � � � � � � � filename
� �� � � � � � � �
Specifies which figure to print. If left out, the currentfigure is printed
� �� � � �
Specifies format (a complete list of available formatsis given as hand-out)
Day 3 – p.142/??
Typing the export command
The device can be:
� �� � � Black-and-white post-script
� �� � � �
Color post-script
� �� � �
�
Post-script level 2
� �� � � � Jpeg image
� �� � � � �
Tiff bitmap
Day 3 – p.143/??
Typing the export command
� � � � � � � � � optional argument specifying additionalproperties of the picture:
� � � � � � �
Append (not overwrite) the graph toPostScript file
� �� � � �
Add TIFF preview
� � � � �� Use CMYK colors instead of RGB
� � � � � � Resolution n dpi
� � � � � ��
Rendering for printing to be done inOpenGL mode
Day 3 – p.144/??
Typing the export command
For example, the command
�� � � � �
� ��
� � � � �� � � �
� � � � � � � � � �exports the plot in figure 2 as a jpeg image with resolution600 dpi and a tiff preview.For a complete list of available options and devices, type’help print’ in the command window.
Example: expfig.m
Day 3 – p.145/??
Importing pictures
Bitmap image files can be imported into Matlab with thefunction imread. The imported picture is then representedas a matrix with each pixel being an element in the matrix.Color bitmaps are represented as an
� � � �
matrix,where the 3 values of each element is the
� � �
color.Grayscale i mages are imported as an
� � matrix, withthe value of each element corresponding to the hue.
A = imread(’Filename’, ’type’)
The imported images can be displayed with the function
image (color) or imagesc (grayscale).
Day 3 – p.146/??
Example
A = imread(’Dilbert.tif’,’tiff’);image(A)A = imread(’Dilbertbw.tif’,’tiff’)imagesc(A)
The function ’imwrite’ can be used to export image matri-ces as bitmaps.
imwrite(A,’filename’, ’type’)
Example: dilbert.m
Day 3 – p.147/??
Movies
A dataset can be displayed as a movie simply by drawing
the set at subsequent times. For larger datasets or com-
plicated plots Matlab can not create the figures sufficiently
fast, and it is best to make the images in advance. The
individual pictures can be saved in any of the file formats
supported by Matlab (not GIF!), and also the movie can be
exported as an AVI movie.
Day 3 – p.148/??
The easy way
The following script draws a contour plot of the diffusionequation:
diffusion.m
In order to make the movie slower the ’pause’ commandcan be used. pause(n) makes a pause of n secondsbefore continuing executing the command:
diffusion2.m
Day 3 – p.149/??
The difficult way
The following script displays a set of images as a movie:
movie(M)
Example: filmspel.m
Day 3 – p.150/??
Creating a set of images
The images used as input in the function ’movie’ shouldbe in the form of
� � � �
matrices, as obtained when animage is imported with the imread command. To makesuch a matrix representation of the current figure thecommand getframe can be used:A = getframe(n);
The command stores the figure with handle n as astructure A. The structure A has two fields:
A.cdata stores the image matrixA.colormap stores the colormap
The image matrix can be extracted from A with thecommandImgmatr = A.cdata;
Day 3 – p.151/??
Input to the movie
The argument M in the command movie(M) is a set ofstructures. Each individual structure is an image, and’movie’ circles through the images dis playing them oneat a time. The set of structures can be obtained by awhile-loop,while t < tmax
T = T+dt*K*del2(T);figure(1), contourf(T);A = getframe(1);M(n) = A;t = t + dt;n = n+1;
end
Day 3 – p.152/??
Input to the movie
However, as is the case with matrices, the resizing of astructure takes a lot of unnecessary CPU-time. Thecommand ’moviein’ creates a set of structures before theloop,M = moviein(N) creates space for
�images in
Example: internvag.m
Day 3 – p.153/??
Playing the movie
Additional arguments can be included in the � � � �
command.
movie(M, n, m) Plays the movie n times,displaying m images persecond
movie(M, -n, m) Plays the movie forwardsand backwards n times
Warning:The Ctrl+C command does not interrupt Matlab in themiddle of a command.
A movie running from the ’movie’ command can therefor
not be stopped.
Day 3 – p.154/??
Converting movie to AVI format
To convert the movie M to an AVI-movie, use the function’movie2avi’:movie2avi(M, ’filename’)saves the movie as filename.avi. It is also possible to
create AVI-movies from separate images with the func-
tions ’avifile’ and ’addframe’.
Day 3 – p.155/??