Introduction to Matlab A. K. Wåhlin J. E. Ø. Nilsen January 2006
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 Topics
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 >> helpdesk in the command window To 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)
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 These were only three of the many possible ways to plot data in Matlab. To get more options, type >> figurepalette in the command window. A new window appears, containing a list of all the workspace variables.
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')
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 Editing plots 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,
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
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 M-file opened with Matlab editor:
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
Statement (two equality signs) assigning a value (one equality sign) 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 = 1is written like this in Matlab code: if a == 2 | b == 0, c = 1; end
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 == 2 returns 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 >= NaN returns ans = 0 (false) Except for the test not equal, which always returns true: >> NaN ~= NaN returns 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)
or right-click on the data in the ‘current directory’ window Import/export of data Data can be imported into Matlab by clicking: Click file menu, then import data
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.