View
224
Download
4
Category
Preview:
Citation preview
Introduction to Matlab
A. K. WåhlinJ. E. Ø. Nilsen
January 2006
Topics
Part I: Introduction Getting started Getting help Plotting M-files & functions
- Why can’t it find my m-file? Loops & logical operators Import/export of data Interpolation Statistics Some tips
Part II: Using Matlab Import/export of data Editing plots Linear algebra Interpolation, curve fitting calculus
Course material
This slide-show
- Examples (matlab code). By clicking the examples you can view them in Matlab and (soon) also run the code.
Hand-outs (more detailed information; lists) Exercises Data-sets needed for exercises Solutions to exercises (matlab code)
How to work with this course 1. Viewing the pps show:
- Start Matlab on your computer- View the show- When an example comes up: Click on the link, which
makes the m-file open in m-editor. Study the code (you can also modify it), then run the example by typing the filename in the Matlab command window.
• 2. Viewing as a webpage:- Start Matlab on your computer- Use the links to the left or arrow keys to change slide- When an example comes up: Open the file manually in
the m-editor. Study the code (you can also modify it), then run the example by typing the filename in the Matlab command window.
Summary
Matlab is easy to use. It is a good tool for checking out different problems when you need a quick, easy way to visualize them.
The big drawback with Matlab has always been the computation speed. The newer versions of Matlab is comparable in speed to Fortran but only if you use it right. It is easy to slow down the program!
For applications when you need to define other classes than matrices Matlab is both slow and difficult.
Getting started
Start Matlab on your computer It should be looking like this A summary of what can be done in the
different menus and windows is given as handout matwin.pdf. A better summary can be found in the Matlab helpfiles.
Demonstration
To go through the demonstration at your own desk: type the commands given in the text-file demo_commands.txt into the command window, one line at the time, and look at the Matlab responses.
A list of all the commands, matlab responses and some comments can be found in demo.pdf
Getting help
Matlab has a very good help/guide with demonstrations, examples, step-by-step guidance, interactive little movies. The guide is much better than this course.
To open it: click in the help menu Or write
>> helpdeskin the command windowTo quickly get help related to a specific function, type
>> help function>> help tan to get help about the tangent
function
Exercises
Exercises (1) – (6) in Exercises_1_to_6.pdf
Solutions: The commands and matlab responses can be found in the text files Sol_1.txt
Sol_2.txt
Sol_3.txt
Sol_4.txt
Sol_5_6.txt
Plotting
Before we go into any details, here is a 'commercial' showing what figures you can make in Matlab.
Type
>> Dif_plots
in the command window.
If the error message
>> Dif_plots
??? Undefined function or variable 'Dif_plots'.
comes up, follow the instructions on next slide. Otherwise, skip ahead!
Plotting: If error here
1. Click on this button in the top of the screen:
2. Find and chose the folder GEO_Matlab_students that you downloaded earlier
3. The 'Current directory' should say GEO_Matlab_students
4. Try again!
Plotting
You have now called the script Dif_plots.m (this will be explained later). Many figure windows have now appeared, and after viewing them you can close them by clicking in the top right corner.
We will now look more closely at three of the plot types. All plot types use arguments, settings etc in the same way.
Plot
Draws a plot of one or several one-dimensional data sets.Example: Type (in the command window)
>> t = linspace(0,5,1000);>> plot(t,sin(t),t,sin(t).*exp(-t))
How to use plot:>> plot(t,f) plots f as a function of t>> plot(t,f,x,y) plots two graphs in the same
window>> plot(A) plots each column of A versus their
index>> plot(t,f,’g:’,x,y,’rx’) changes the linetype and color
Type ’help plot’ for a complete list of available linetypes.
Surf
A matrix can be visualized as a surface with the command surf:
Example: Type (in the command window)>> z = peaks;>> surf(z)
How to use surf:>> surf(z) Draws the surface z versus the row- and column indices>> surf(x,y,z) Draws the surface versus x and y>> surf(x,y,z,C) Uses the color map specified in C
Type 'help surf' for more options.
Contour
Another way to visualize a matrix is by drawing a contour plot with the command contour. Example: Type (in the command window)
>> z = peaks; >> contour(z,[0,0.2,0.3,0.5,1,3])
The command contour has many optional arguments:>> contour(z) Draws a contour plot versus the row and column index>> contour(x, y,z) Contour plot versus x and y>> contour(z,N) Draws N evenly spaced contour lines>> contour(z,[z0, z1, z2, ...,zN]) Draws the contour lines z0, z1, z2 etc>> contour(x,y,z,[z0 z0]) Draws a single contour line, z = z0.
To create a filled contourplot, use the function contourf.Example: Type (in the command window)>> figure(2), contourf(z,30)
Plotting
These were only three of the many possible ways to plot data in Matlab. To get more options, type
>> figurepalettein the command window. A
new window appears, containing a list of all the workspace variables.
Right-click on one of the workspace variables and chose 'more plots'.
to get a complete, illustrative list of all possible ways to plot the data - sorted under line plots, surface plots etc
Plotting
You can also add things to your plot. To add a label on the x-axis, type
>> xlabel('Text here')To add a label on the y-axis, type>> ylabel('Text here')To add a title, type>> title('Title here')To add a legend, type>> legend('Data1','Data2','etc')
The plot can be edited from the edit menu in the figure window. Click on the object that you want to edit (e.g. the plotted line). Then go to the Edit menu,
Editing plots
and chose edit Current Object Properties.
A new window opens, in which you can change linestyle, color, thickness etc etc.
By marking other objects you can edit these too -
here e.g. font, fontsize and weight
Exercises
Plotting exercises: Exercises (7) – (11) in Exercises_7_to_11.pdf.
Solutions: The commands and matlab responses can be found in the text file
Sol_7_11.txt
M-file
An m-file is a text file with extension .m It can be used to store matlab commands Matlab reads and executes the commands in
an m-file if you type the name of the file in the command window.
It can be created/edited in an ordinary text editor, or in the Matlab editor.
From the Matlab editor the file can be run directly, by pressing F5 (or clicking in the Debug menu)
Different ways to create an m-file
Use an ordinary text editor and save the file using fileextension .m: filename.m
Choose ’new file’ under the File Menu If you have already typed the commands in
the command-window, you can mark them in the history window and then right-click. The option ’make m-file’ then appears
M-file opened with Matlab editor:
Things written behind a % are not executed (commenting). Green colour text in m-editor
The sign ; suppresses printing of the answer in the command window
Examples m-files
Try executing (by typing the filename in the command window) this m-file: myfile.m
Try executing this m-file: myfile2.m
Why does it not work?
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 in the current directory?3. Is there an m-file called that somewhere else?
When Matlab searches for the m-file it looks in specific folders, its search path. If the folder is not added to the path Matlab can not run your script.
Why does it not work?
Matlab can not find m-files that are not located in the search path:
Change the search path
Change the current directory by clicking
Add the path to the
search path by clicking
Change the search path
Can also be done by typing commands:
>> addpath C:\Folder\Folder2
>> path(path,'C:\Folder\Folder2')
Matlab first searches in the current directory, then along the search path
Change the search path
The added path will not be found by Matlab the next time you start the program. In order to make permanent changes to Matlab’s search path you can
- Type savepath before you quit Matlab- 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
Functions
A function is an m-file starting with the word ’function’ Examples: spir.m
spirplot.m
spir3.m A function has its own ’local’ workspace. Variables
defined in the function are not stored in the ordinary workspace. A function does not assign any values to anything - except for the output.
Functions, too, must be in the search path
Plotting
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 subplot(M,N,p) divides the window into MxN plotting areas and performs the plot command in the p’th area.
Example: threeplots.m
Exercises
Scripts and functions exercises: Exercises (12) – (16) in Exercises_12_to_16.pdf.
Suggestions to solutions can be found in these m-files:(12): Sol_12.m(13): expsin.m(14): Sol_14.m(15): (i) sinexp_i.m
(ii) sinexp_ii.m(16): Sol_16.m
Loops & logical operators
A for-loop begins with the word ’for’, ends with the word ’end’. Example: forloop.m
The loops can be written directly in the command window:
>> for n = 1:100, t(n) = 1/n; end>> for r = linspace(0,1,20), q = sin(r); end>> A = rand(100,100); for a = A, plot(a), end
Commas separate several commands on a line. If A is a matrix the loop variable becomes a vector of
the separate columns in A. Example: forloop2.m
Loops and logical operators
A while-loop performs a task until a logical test proves false. Begins with the word ’while’, ends with the word ’end’
while t < tmax,
a = sin(t);
t = t + dt;
end
Loops and logical operators
More examples: whileloops.m
Emergency exit: Ctrl+C
If you want to interrupt a loop while it is running, type Ctrl+C.
If you are working on a remote computer, try giving the Ctrl+C command in the window that controls the remote access (e. g. the xterm-window) rather than in the Matlab command window.
Logical tests
Logical tests returns 0 if the test proved false and 1 if it proved true. Common tests:
== Equal~= Not equal> Larger than< Smaller than
Combinations:| Or& And
A list containing more logical tests is given as handout logical_test.pdf
Logical tests
Branch statements: Perform a task if a logical test prove true and skips the task if it prove false. Begins with the word ’if’, followed by a logical test, and ends with the word ’end’.
The statement if a = 2 or b = 0, then c = 1 is written like this in Matlab code:
if a == 2 | b == 0,
c = 1;
endStatement (two equality signs)
assigning a value (one equality sign)
Logical tests
When logical tests are performed on a matrix, a logical matrix is returned. A scalar can be compared to any matrix, but two matrices can only be compared if they are the same size. There are special matrix-tests that return a single value, for example the function isequal that returns 1 if the two matrices are of the same size and all elements are equal.
Logical tests
Example:
>> A = [0 2 3;2 3 4]; A == 2returns
ans =[0 1 0;1 0 0]
>> A = [0 2 3;2 3 4]; isequal(A,2)returns
ans =0
A summary of matrix logical tests can be found in logical_tests.pdf
Logical tests: Warning
Any test performed on anything containing a NaN (Not-a-Number) returns false!
>> Inf >= NaNreturns
ans = 0 (false)
Except for the test not equal, which always returns true:
>> NaN ~= NaNreturns 1 (true)
Exercises
Logical tests and loops exercises, (17) – (23) can be found in Exercises_17_to_23.pdf
Suggestions to solutions can be found in these m-files:(17): Sol_17.m(18): Sol_18.m and ex18.m(19): Sol_19.m(20): Sol_20.m(21): Sol_21.m(22): Sol_22.m(23): Sol_23.m
Import/export of data
Matlab supports most common data formats, for example binary, ascii, CDF, Excel worksheet as well as Matlabs ’own’ type mat-file (binary). A list of all compatible types is given as hand-out (Data_formats.pdf)
Import/export of data
Click file menu, then import data
Data can be imported into Matlab by clicking:
or right-click on the data in the ‘current directory’ window
Import/export of data
Before moving on to written commands: Practice by importing the files 'VIK_1990.dat', 'VM_Hydr.mat' and 'Foraminifers.xls' into the workspace.
Import/export of data
Clicking does not work with binary data, or for exporting data except in mat-format.
Data can also be imported by typing commands. The commands vary depending on format. Here we use two common formats: -mat and -ascii. More formats will be dealt with later on in the course. A list of some formats and the commands by which to import them is given in Data_formats.pdf
Import/export data
To import data with matlabs own format, .mat, use the import wizard or the command load:
>> load VMhydr
loads the file VMhydr.mat with all variables into the workspace.
Example: load_VM_mat.m To export mat-files, use the command save:
>> save filename x y
Import/export of data
Import/export of ascii- formatted data: Add –ascii after the load/save command:>> save filename A –ascii>> load filename –ascii
Example: load_VM_ascii.m (load the ascii-formatted data stored in the two files VMSalt.dat and VMDepth.dat; then plots and saves the data in a single ascii-formatted file)
Exercises
Import/export of data, (24) – (33) can be found in Exercises_24_to_33.pdf.
Suggestions to solutions can be found in these m-files:
(24-25): Sol_24_25.m
(26): Sol_26.m
(27): Sol_27.m
(28-30): Sol_28_30.m
(31-33): Sol_31_33.m
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 irregularly spaced. Linear interpolation is performed by default, but other methods can be used by specifying a ’method’ input in the interp functions.
Interpolation
One-dimensional interpolation is performed by use of the function interp1:
>> Yi = interp1(x,y,Xi,’method’)
takes the original data y (measured at points x) and interpolates them at values Xi using the specified method.
Example: intp.m
Interpolation
Two-dimensional interpolation is performed by use of the function interp2.
>> Zi = interp2(x,y,z,Xi,Yi)
takes the original data z (measured at points (x,y)) and interpolates it to the points (Xi,Yi). Xi can be a row vector and Yi a column vector describing the new grid.
Interpolation
>> Zi = interp2(x,y,z,Xi,Yi,’spline’)
uses spline interpolation instead of the default (linear)
>> Zi = interp2(z,N)
Example: intp2D.m
Exercises
Interpolation, (34) – (35) can be found in
Exercises_34_to_35.pdf.
Suggestions to solutions can be found in these m-files:
(34): Sol_34.m
(35): Sol_35.m
Debugging tools
Give control to the command window to examine and change variables in the function workspace:
>> keyboard
Return and continue executing the script:
>> return
Stop the execution of a script and display an error message:
>> error('Your message here')
Things to help find the errors
Document your scripts and functions: Add comments and help. If the first lines in an m-file are commented, these will be displayed in the command window when you type help filename
Think about what is best, function or script
- Functions are a little slower CPU-wise (but may still save time if used often)
- The good thing with functions is that they do not assign any values to anything
Things to help find the errors
Have a system when you name your variables. Matlab 'tradition':
- Matrix: Capital letters
- Natural numbers: m, n, p, q
- Global variables: long names with capital letters
- Handles: H_id Read the manual (or visit helpdesk) regularly
Save CPU-time
With optimal use, Matlab is comparable in speed to Fortran. However, it is easy to make Matlab very slow. The speed issue seems to get better each new release. Some rules of thumb:
Do not resize matrices in loops - define the matrix before the loop (same as preallocating memory).Example: resizeloop2.m
Matrices are sometimes faster to compute compared to element-wise computation in a loop.
User defined functions usually take a little longer than built-in functions ....Example: userfun1.m
..but may take a LOT longer if the function is called often (e.g. if not vectorized code)Example: userfun2.m
Save CPU-time
The new Matlab (comparable in speed to Fortran) has accelerated loops that computes almost as fast as vectorized code. However, the accelerated loops only work with built -in functions. Furthermore, it does not work for all datatypes. Although all common datatypes are included it is important that there is no confusion over which datatype is used. For example, 2*i is not accelerated but 2i is.
If accelerated code is ’interrupted’ by an unaccelerated command, the rest of that line executes as ’slow’ code (Matlab 5 speed).Example: Acctest.m
Part II: Using Matlab
Part I: Introduction Getting started Getting help Plotting results M-files & functions Why can’t it find my m-file? Loops & logical operators Import/export of data Interpolation Save time & save CPU time
Part II: Using Matlab Import/export of data
- Ascii- Binary- netCDF
Editing plots- handles- 2 and more y-axes- 3D graphics- import/export graphics- movies
Linear algebra statistics, interpolation, curve
fitting Calculus
Import/export of data
Click file menu, then import data
Data can be imported into Matlab by clicking:
or right-click on the data in the ‘current directory’ window
Import/export of data
In the course folder there are 12 ascii-formatted datafiles, VIK_1990.dat up to VIK_2001.dat. Since there are so many files it is easier to write a script for importing them.
Import/export of –ascii formatted data: Add –ascii after the load/save command:
>> save filename A –ascii>> load filename –ascii
* Example: try1.m (load the ascii-formatted data stored in VIK_1990.dat)
Import/export of data
The reason we fail to load the data is that load requires that the number of columns are equal for all rows.
Instead we try dlmread, which works for delimited textfiles:>> A = dlmread(’filename’,’delimiter’)
Reads the file ’filename’ into the variable A
delimiter can be anything, e. g.’ ’ = space delimited’\t’ = tab delimited
Example: try2.m (load the ascii-formatted data stored in VIK_1990.dat)
Import/export of data
The reason we fail this time is the column headers in the datafile. We try adding more arguments in dlmread:
A = dlmread(’filename’,’delimiter’,RANGE)Reads a portion of the file ’filename’ into the variable A.RANGE = [Rstart Cstart Rend Cend] specifies the row R
and column C where to start and end reading. It can be noted that R and C start at zero, i. e. Cstart = 0 indicates the first column and so on.
dlmread fills empty places in the data with zerosdlmwrite(’filename’,Var,’delimiter’) writes the variable Var
into the file ’filname’ using the specified delimiter
Example: try3.m
Import/export of data
Now we can write a script that loads all 12 years of sealevel data:
Example: readfiles.m
Binary files
fid = fopen(’filename’,’permission’)A = fread(fid,size,precision)Reads the data in file ’filename’ into the variable
Afid = fopen(’filename’,’permission’)fwrite(fid,A,precision)Writes the variable A with the desired precision
into the file ’filename’. The data is written in column order.
Binary files
Example reading binary data: binread.m
Example writing binary data: binwrite.m
>> help iofun
for more information about import/export of data
NetCDF
Coming...
Webpage:http://www.marine.csiro.au/sw/matlab-
netcdf.html
Download a toolbox mexnc to handle NetCDF. This toolbox is not very user-friendly, but there are several different (free) packs that make it easier to use.
Exercises
Import/export of data, (36) – (39) can be found in
Exercises_36_to_39.pdf
Suggestions to solutions can be found in these m-files:
(36): Sol_36.m
(37): Sol_37.m
(38)-(39): Sol_38_39.m
Editing plots
All the parameters that can be edited from the plot window can also be adjusted directly when the plot is drawn. This is done by including additional string arguments in the plot command.
>> plot(x,y,’LineWidth’,2,’Color’,[0 0 1],’LineStyle’,’--’)
A color is specified by three numbers corresponding to the RGB color values.
>> surf(x,y,z,’LineStyle’,’none’,’FaceColor’,’interp’)
Editing plots
Examples (changes that were made interactively in the demonstration of the figure window):
plotex2.m
surfex2.m
contex2.m
Editing plots
If we want to remove the lines in a color plot (pcolor) by typing
>> pcolor(x,y,z,’LineStyle’,’none’)
it does not work. This is an example of when it is good to use handle graphics.
Example: contex3.m
Handles to help edit the figure
A handle is a number that helps Matlab keep track of the different plots, axes, figure windows etc (’objects’). In the Matlab help 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 ’parent’ to the figure and the screen handle is parent to the figure handle.
Handles
To find a handle, simply write a parameter name in front of your plot command.
>> Hl_xy = plot(x,y);
A handle called ’Hl_xy’ has been created. The handle identifies the plot.
>> Hf_fig = figure(1);
A handle called ’Hf_fig’ identifying the figure window has been created.
OR: Mark the object and then ask for the handle using the command gco (get-current-object)
>> gco
Handles
With the handle the plot can be edited. 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 the handle properties.
>> get(Hl_xy) displays a complete list of the properties of the object with handle Hl_xy
Example: hangr1.m
Handles
Ha_ax = axesThis way the handle to the object ’axes’ is
created (not to be confused with the command axis!). Axes is an important object that is parent to all surfaces, lines etc in the plot. The handle to the current axes object can also be obtained with the function gca (get-current-axes):
Ha_ax = gca
Handles
When handles are used to edit the plot it can be confusing which handle should be used (i. e. which properties belong to which object). 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).
Handles
One plot command can create several objects. In this case a column vector of all the handles are created:
>> Hl_peaks = plot(peaks);
returns a column matrix of 50 handles. The handle properties can be adjusted one by one,
>> set(Hl_peaks(n),’LineWidth’, 2)
or all together
>> set(Hl_peaks,’LineWidth’, 2)
Handles: The exception
The functions ’contour’ and ’contourf’ are special in that they have an optional function output - the coordinates of the calculated contours. The command
>> c = contour(z)does not return a handle, but a 2*N matrix containing
the contour coordinates. To obtain the handle of the contour plot two arguments must be specified:
>> [c, Hl_cont] = contour(z)returns the handles of the created lines in the column
vector Hl_cont.
Example: contex4.m
More about handles...
The properties of an object can also be stored. This can be useful if a plot is edited ’by hand’ and the new settings are to be applied to subsequent figures. The command
>> Prop_H = get(Hl_cont)
stores the properties of the object in Prop_H.
More about handles...
The parameter Prop_H is a new type of variable - a ’structure’. The values stored in it are not identified by indices (as in matrices) but by the value name. For example,
>> Prop_H.Color
returns the line color value.
>> Prop_H.LineWidth
returns the line width.
Example prop1.m
More about handles..
The next time you want to make a figure with the same settings, load the old handle properties into the workspace and apply them to the new figure:
Ht_new = title(’New plot’);set(Ht_new,Oldprop)Hs_new = surf(Newdata);set(Hs_new,Oldprop)Example: hangr13.m
More about handles...
To get a list of all the ’settable’ properties of a handle, type
>> set(Hx_obj)
to list all the properties that are possible to modify
>> get(Hx_obj)
to display a list of all the object properties
3D-graphics: Slice
One way to visualize three-dimensional data is by drawing 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 the planes x = Xp, y = Yp and z = Zp. Several planes can be used.
slice(V,Np,Mp,Qp) draws contour plots of V versus its index.
Example: sliceex.m
3D-graphics: Patch
A three-dimensional data set can also be visualised by drawing one of the isosurfaces. The function patch displays an isosurface. In order to find the surface the function isosurface can be used. The values at the edges of 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
Plotting: Two y-axes
Example: Weather_obs1.m
The data is better visualized with two separate y-axes. To plot data with two y-axes, use the command plotyy:
>> plotyy(x1,y1,x2,y2)
Example: Weather_obs2.m
Use the handles to adjust axes limits etc.
More than two y-axes:
To plot more than two y-axes we must use handles and the low-level line and axis commands.
Detailed step-by-step instructions can be found in the Matlab help: Graphics - Axis properties - Using Multiple X- and Y-axis.
Here we will instead make use of two scripts constructed by Blair Greenan:
floataxisxfloataxisy..including a fix by Even Nilsen that requires the function
mima.mAll three files are in the course folder
More than two y-axes
These two scripts can be downloaded for example fromhttp://www.mathworks.com/matlabcentral/..together with many other useful scripts.Usage:To add a new y-axis write >> floataxisy(x1,y1)instead of the regular plot commandTo add a new x-axis write>> floataxisx(x1,y1)All the regular plot commands work.Example: Weather_obs3.m
Export graphics
A plot can be exported in a number of different picture formats. This can be done either from the File menu (chose ’export setup’, which opens a new window, then click 'export') or by written commands. The written commands give more options and settings.
Export graphics by typing
The command ’print’ is used to export a figure from Matlab. Usage:
>> print -f<handle> -device -options filename
-f<handle> specifies the figure, ex. -f2 means figure(2)
Export graphics by typing
>> print -f<handle> -device -options filename
-device specifes format. For example:
-dps Black-and-white postscript
-dpsc Color postscript
-dpsc2 Postscript level 2
-djpeg Jpeg image
-dtif Tiff bitmap
type help print for a complete list of available formats
Export graphics by typing
>> print -f<handle> -device -options filename-options optional argument specifying additional
properties of the picture, for example:-append Append (not overwrite) the graph to PostScript
file-tiff Add TIFF preview (to encapsulated
postscripts)-cmyk Use CMYK colors instead of RGB-r<nn> Resolution nn (in dpi)-opengl Rendering for printing to be done in
OpenGL mode
Export graphics by typing
For example, the command
>> print -f2 -djpeg -r600 myfig.jpg
exports the plot in figure 2 to file myfig.jpg as a jpeg image with resolution 600 dpi.
For a complete list of available options and devices, type ’help print’ in the command window.
Example: Expfig.m
Importing pictures
Bitmap image files can be imported into Matlab with the function imread. The imported picture ([NxM] pixels) is then represented as a matrix with each pixel being an element in the matrix. Color bitmaps are represented as an [NxMx3] matrix, where the 3 values of each element is the RGB color values.
Grayscale images are imported as an [NxM] matrix, with the value of each element corresponding to the hue.
>> A = imread(’Filename’, ’type’)The picture matrix A can then be viewed using
image (color) or imagesc (grayscale).
Importing pictures
Example: dilbert.m
The function ’imwrite’ can also be used to export image matrices as bitmaps directly.
>> imwrite(A,’filename’, ’type’)
Exercises: Graphics
Exercises Graphics, (40) - (43), can be found in Exercises_40_to_43.pdf
Suggestions how to solve the exercises:
(40): Sol_40.m
(41): Sol_41.m
(42): Sol_42.m
(43): Sol_43.m
Movies
A dataset can be displayed as a movie simply by drawing the set at subsequent times. For larger datasets or complicated 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.
Movies
The following script draws subsequent contour plots of the diffusion equation:
diffusion.m
These images can all be stored in a movie-matrix M. To view the images as a movie, use the command movie:
>> movie(M)
Movies
The images used as input in the function ’movie’ should be in the form of NxMx3 matrices, as obtained when an image is imported with the imread command. To make such a matrix representation of the current figure, use the command getframe:
A = getframe(n);
The command stores the figure with handle n as a structure A. The structure A has two fields:
A.cdata stores the image matrix
A.colormap stores the colormap
Movies
The argument M in the command movie(M) is a set of structures. Each individual structure is an image, and ’movie’ circles through the images displaying them one at a time. The set of structures can be obtained by a loop,
for n = 1:100figure(1), contourf(T(n));A = getframe(1);M(n) = A;
end
Movies
However, as is the case with matrices, the resizing of a structure takes a lot of CPU-time. The command ’moviein’ presizes the movie,
>> M = moviein(N) creates space for N images in the movie M
Example: internvag.m
Movies
Additional arguments can be included in the movie command:
>> movie(M,n,m) Plays the movie n times, displaying m images per second
>> movie(M, -n, m) Plays the movie forwards and backwards n times
Warning:
The Ctrl+C command does not interrupt Matlab in the middle of a command. A movie running from the ’movie’ command can therefore not be stopped.
Movies
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 functions ’avifile’ and ’addframe’.
Example: make_avi.m
Movies
When the workspace memory becomes full Matlab becomes slow and unreliable. This may become a problem with movies since these take a lot of workspace memory. However, if the aim is to produce an avi-file movie it is not necessary to have the whole movie prepared at once. By using the function addframe it is possible to add frames one by one instead.
>> addframe(aviobj,F);
adds the frame(s) F to the end of the avi movie associated with aviobj.
Movies
The aviobj is defined beforehand using the function avifile,
>> aviobj = avifile(filename);creates an avifile filename.avi and sets the identifier to
aviobj.>> aviobj = avifile(filename,'fps',20);creates an avifile filename.avi, sets the identifier to
aviobj and the frames-per-second rate to 20. For other optional arguments:
>> help avifileExample: make_avi_frame.m
Exercises: Movies
Exercises Movies, (44) - (46), can be found in
Exercises_44_to_46.pdf
Suggestions how to solve the exercises:
(44): Sol_44.m
(45): Sol_45.m
(46): Sol_46.m
Matrix Laborations
Besides the elementary functions that are defined for scalars (and operate element-wise on the matrix) there are several functions that are specific for matrices. The most important of these are given as hand-out. A few will now be demonstrated using a linear equation system as example. Consider the system of linear equations,
1 2 3
1 2 3
1 2 3
3 2 39
2 3 34
2 2 26
x x x
x x x
x x x
Matrix Laborations
Besides the elementary functions that are defined for scalars (and operate element-wise on the matrix) there are several functions that are specific for matrices. The most important of these are given as hand-out. A few will now be demonstrated using a linear equation system as example. Consider the system of linear equations,
1 2 3
1 2 3
1 2 3
3 2 39
2 3 34
2 2 26
x x x
x x x
x x x
Matrix Laborations
Using matrix notation the system can also be written
Ax = b
where
3 2 1
2 3 1
1 2 3
A
1
2
3
x
x x
x
39
34
26
b
The solution to the system is given by
x = A-1*b
Matrix Laborations
In Matlab there are two ways of solving this problem.
1) Calculate the inverse of A, A-1, then left-multiplication of b with A-1:
>> x = inv(A)*b;
2) Left-division of b with A:
>> x = b\A;
Example: Solvetime.m
Matrix laborations
Matlab can also handle overdetermined equation systems. The optimal solution (in a least-square sense) is then found.
Example: overdet.m
NOTE: No warning message is displayed, even though the 'solution' calculated by Matlab is only a least-square fit to the equation system.
Exercises: Matrices
Exercises Matrices, (47) - (50), can be found in
Exercises_47_to_50.pdf
Suggestions how to solve the exercises:
(47-48): Sol_47_48.m
(49): Sol_49.m
(50): Sol_50.m
Statistics
Matlab has several statistical functions included, type 'help stats' to get a complete list. Some statistical functions return a scalar number when applied to a vector. If these are applied to a matrix, a row vector containing the results from each of the columns is instead returned.
Only one example: stat1.m
Statistics: NaN
Missing data points in a series are commonly replaced with NaN (because these are not plotted with the regular plotting routines). No statistical functions work on these sets, since a mathematical operation on NaN always returns NaN.
Try removing all points with NaN (use e.g. the isnan function) or use the special functions that are defined for such series, for example nanmax, nanmean etc.
Curve fitting: Polynomials
A dataset may be fitted into a polynomial of degree N by use of the function polyfit. The error is minimized in a least square-sense.
>> A = polyfit(y,x,N)
returns the coefficients of the polynomial yP(x),
where A = [aN,aN-1,...,a2,a1,a0]
Examples: cfit1.m and cfit2.m
1 21 2 1 0( ) ...N N
P N Ny x a x a x a x a x a
Curve fitting: Fourier series
Matlab uses the complex discrete Fourier transform,
where x is an equally spaced data set of N points. A spectrum of a time series may be obtained from the absolute value of the discrete Fourier transform. To obtain the Fourier transform, use the function fft (onedimensional), fft2 (two-dimensional) or fftn (n-dimensional). To obtain the inverse, use ifft (one-dimensional), ifft2 (two-dimensional) or ifftn (ndimensional).
Example: spektrum.m
( 1)( 1)2
1
( ) ( )k nN xiN
n
X k x n e
1 k N
Curve fitting: Other functions
The built-in routines for solving over-determined equation systems can be used to fit a data set to a linear combination of arbitrary functions. Instead of polynomials or sine/cosines, use a sum of arbitrary functions,
The coefficients cn are to be determined so that the error is minimized.
1 1 2 2 1 1( ) ( ) ... ( ) ( )A N N N Ny x c f x c f x c f x c f x
Curve fitting: Other functions
By computing the function values at each data point an over-determined equation system Ac=y is obtained, where
The system is 'solved' in Matlab and the coefficients cn determined by
>> c = y\A
1 1 2 1 1
1 2 2 2 2
1 1
( ) ( ) ... ( )
( ) ( ) ... ( )
... ... ... ...
( ) ( ) ... ( )
N
N
N N N M
f x f x f x
f x f x f xA
f x f x f x
1
2
...
N
c
cc
c
1
2
...
M
y
yy
y
Interpolation
One-dimensional interpolation:
>> Yi = interp1(x,y,Xi,’method’)
Two-dimensional interpolation:
>> Zi = interp2(x,y,z,Xi,Yi)
Three-dimensional interpolation:
>> Ui = interp3(x,y,z,U,Xi,Yi,Zi)
N-dimensional interpolation:
>> Ui = interpN(X1,X2,X3,...,U,X1i,X2i,X3i,...)
Example: irrdata.m
Interpolation: Irregular data sets
The data must be sorted in ascending order for use in the interp.. functions. One-dimensional data sets can be sorted, using the function sort before the interpolation is performed if need be:
>> Xs = sort(x);sorts the elements in vector x in ascending order and stores
them in vector Xs.>> [Xs,I] = sort(x);sorts the elements and also stores the indices in vector I.>> [Xs,I] = sort(x); Ys = y(I);uses the stored indices to rearrange the corresponding y-
values. The data y that were sampled at (irregular) points x hve been rearranged in the vector Ys sampled at (ascending) points Xs.
Interpolation: Irregular data sets
For two or more dimensions it gets more complicated to sort the data. The function griddata may be used instead.
In two dimensions:
>> Zi = griddata(x,y,z,xi,yi,'method')
In three dimension:
>> Ui = griddata3(x,y,z,U,xi,yi,zi,'method')
In N dimensions:
>> Ui = griddataN(x1,x2,x3,...,U,x1i,x2i,x3i,...,'method')
Example: irrdata2.m
Exercises: Curve fitting & interpolation
Exercises Curve fitting and interpolation, (51) - (54), can be found in
Exercises_51_to_54.pdf
Suggestions how to solve the exercises:
Analytical toolbox
With the analytical toolbox, equations can be solved analytically. All common operations can be done on analytical objects, for example factorization, derivation and integration. The analytical toolbox builds on Maple, and uses Maples commands. A symbolic object is defined by use of the command ’sym’ or ’syms’:
>> x = sym(’x’) Defines x as symbolic object
>> syms x y f Defines x,y and f symbolic obj.
Example: demoan.m
Analytical toolbox: Integration
The function ’int’ integrates a function analytically. If no
analytical integral can be found, the input is returned.
Usage:>> h = int(f); integrates the equation f with
respect to the dependent variable>> h = int(f,y); integrates the equation f
with respect to yExample: anin.m
Analytical toolbox: Derivation
The function ’diff’ calculates the derivative of a function analytically.
Usage:
>> g = diff(f) Derivates with respect to the dependent variable
>> g = diff(f,y) Derivatews with respect to y
Example: ande.m
Analytical toolbox: Root-finding
The function ’solve’ is used to find the root to the equation f(x) = 0.
Usage:
>> a = solve(f); Solves f(x) = 0
>> a = solve(’f(x)=3’); Solves f(x) = 3
Example anro.m
Numerical integration & 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.
Numerical integration
Suppose we have sampled a signal A(t) at time interval Δt. An estimate of the time integral of the data set is then given by
Three different ways of performing the above summation in Matlab will now be presented.
10
( ) ( )t N
n
A d A n t
Numerical integration
1. For-loop:>> int = dt*A(1)>> for n = 2:N>> int = dt*A(n) + int;>> end2. Using the sum-function:>> int = dt*A(1)*sum(A);3. Trapezoidal estimate (trapz):>> int = trapz(A);>> int = trapz(t,A);Example numint.m
Numerical integration
To find the integral of an analytical function, use e.g. the quad or quadl functions (type help quad for more options). Usage:
>> int = quad(’fun’,a,b); Adaptive Simpson quadrature. fun is the name of the function (can be a user-defined m-file), a and b are integration limits.
>> int = quadl(’fun’,a,b); Adaptive lobatto quadrature. fun is the name of the function (can be a user-defined m-file), a and b are integration limits.
Example: numpr2.m
The function diff can also calculate the numerical derivative. Usage:
>> der = diff(f);Calculates the differenceder(n) = f(n+1)-f(n)>> diff(f,M) Performs the differencing M times
recursively>> diff(B), where B is a matrix, performs the
differentiation along each row.>> diff(C), where C is an N-dimensional matrix,
performs the differentiation along the first non-singleton dimension
Numerical derivation
Calculus
This course has dealt with data treatment in Matlab: import/export of data, visualizing and basic data analyses.
For more information and examples about mathematical tools, look in the helpdesk. There is also a slide-show about solving ODEs in Matlab included in this folder, ODE_UiO_2003.pdf (it is part of a more extensive course, Matlab_UiO_2003.pdf, also included)
Thank you
The end
Recommended