• No results found

Geology & Geophysics Matlab Tutorial.pdf

N/A
N/A
Protected

Academic year: 2021

Share "Geology & Geophysics Matlab Tutorial.pdf"

Copied!
16
0
0

Loading.... (view fulltext now)

Full text

(1)

G & G Matlab Tutorial

G & G Matlab Tutorial

Original version from Geology 392 tutorial; it has now been heavily modified. See the end for current maintainer. Original version from Geology 392 tutorial; it has now been heavily modified. See the end for current maintainer.

Plot of the Matlab peaks() function; a sample function for 3d graphics built from translated and scaled Plot of the Matlab peaks() function; a sample function for 3d graphics built from translated and scaled

Gaussians. Gaussians.

Getting Started

Getting Started

In general, Matlab is run by selecting the application from a menu, or typing

In general, Matlab is run by selecting the application from a menu, or typing matlabmatlab at the command line prompt at the command line prompt in a UNIX environment. Once running, Matlab is itself a command line program, wherein you will be given a in a UNIX environment. Once running, Matlab is itself a command line program, wherein you will be given a  prompt

 prompt to to type type in in specific specific commands.commands.

You should see a graphics window flash up on the screen and then disappear. If so, you are all set; otherwise you You should see a graphics window flash up on the screen and then disappear. If so, you are all set; otherwise you need to check that you have set your display variables properly. If you can't get the graphics to appear on the need to check that you have set your display variables properly. If you can't get the graphics to appear on the screen, Matlab should work, but without any plotting.

screen, Matlab should work, but without any plotting.

To see the graphics window, you just need to plot something. Try typing To see the graphics window, you just need to plot something. Try typing

>> plot(1:0.5:5) >> plot(1:0.5:5)

(2)

which will plot the numbers 1 to 5 (counting by 0.5) by their index (1 to 9). As you'll see later, the colon (:) is a which will plot the numbers 1 to 5 (counting by 0.5) by their index (1 to 9). As you'll see later, the colon (:) is a shorthand for creating a vector of numbers. You will use it a lot in Matlab.

shorthand for creating a vector of numbers. You will use it a lot in Matlab.

What is Matlab?

What is Matlab?

Matlab is a program for doing scientific calculations using matrices. The matrix is the basic data type of matlab, Matlab is a program for doing scientific calculations using matrices. The matrix is the basic data type of matlab, and it may be real or complex. Matlab only uses double-precision floating point numbers; there are no integer  and it may be real or complex. Matlab only uses double-precision floating point numbers; there are no integer  matrices. You can also use scalars (1 x 1 matrices) or vectors (n x 1 or 1 x n matrices). What makes Matlab very matrices. You can also use scalars (1 x 1 matrices) or vectors (n x 1 or 1 x n matrices). What makes Matlab very  powerful

 powerful is thais that yt you ou can can perform perform operations operations on on whole whole vectors vectors or or matrices at matrices at one one time, without time, without having having to to looploop through each element. Matlab is also quite good at plotting data (in 2- and 3-d), which makes it useful for  through each element. Matlab is also quite good at plotting data (in 2- and 3-d), which makes it useful for   plotting

 plotting data data generated generated elsewhere.elsewhere.

In this tutorial, we'll go over some of the basic commands, how to read in data, how to save data, how to plot In this tutorial, we'll go over some of the basic commands, how to read in data, how to save data, how to plot data, and how to create simple programs, called

data, and how to create simple programs, called m-filesm-files..

Getting Help in Matlab

Getting Help in Matlab

If you get stuck or just need more information about Matlab, there are a number of different resources. The If you get stuck or just need more information about Matlab, there are a number of different resources. The easiest one to use is built into Matlab itself. By typing

easiest one to use is built into Matlab itself. By typing helphelp ororhelphelp command command , you can get a description of a, you can get a description of a command or group of commands. Try typing

command or group of commands. Try typing

>> help graph2d >> help graph2d

This gives you a list of all of the 2-dimensional plotting functions available. Another helpful command is the This gives you a list of all of the 2-dimensional plotting functions available. Another helpful command is the

lookfor

lookfor command. By typing command. By typinglookforlookfor keyword keyword , you will get a list of all commands related to, you will get a list of all commands related to keyword keyword , even if , even if  you aren't sure of the exact function name.

you aren't sure of the exact function name.

There are also a number of books, including the Matlab manual and

There are also a number of books, including the Matlab manual and Getting Started in MatlabGetting Started in Matlab by Rudra Pratap. by Rudra Pratap. The Mathworks (developers of Matlab) WWW site,

The Mathworks (developers of Matlab) WWW site, http://www.mathworks.comhttp://www.mathworks.com, has extensive documentation, has extensive documentation available (under Support). The documentation for Matlab (but not the toolboxes or other Mathworks products) is available (under Support). The documentation for Matlab (but not the toolboxes or other Mathworks products) is available

available herehere. For users who wish to kill a forest of trees for paper manuals, they are available for order from. For users who wish to kill a forest of trees for paper manuals, they are available for order from Mathworks, or as PDF files on the web

Mathworks, or as PDF files on the web herehere..

Dealing With Variables

Dealing With Variables

Here's a short tutorial on working with variables, taken from the book,

Here's a short tutorial on working with variables, taken from the book, Getting Started in MatlabGetting Started in Matlab. It is. It is highlyhighly recommended that you obtain this book as it will make your life in Matlab easier. Variables in Matlab can have recommended that you obtain this book as it will make your life in Matlab easier. Variables in Matlab can have any name, but if the variable has the same name as a function, that function will be unavailable while the

any name, but if the variable has the same name as a function, that function will be unavailable while the variable exists. Try typing the following into Matlab:

variable exists. Try typing the following into Matlab:

>>

>> 2+2 2+2 % % Add Add two two numbersnumbers

% % ans

ans = = % % Matlab Matlab uses uses 'ans' 'ans' ifif

% there is no variable % there is no variable 4

4 % % assignment assignment (lvalue)(lvalue)

>>

>> x= x= 2+2 2+2 % % Assigns Assigns the the resultresult % to variable 'x' % to variable 'x' x

x = = % % and and displays displays thethe

% value of 'x' % value of 'x' 4

4 %%

>>

>> y=2^2 y=2^2 + + log(pi)*sin(log(pi)*sin(x); x); % % The The semicolon semicolon atat >>

(3)

%

% To To see see the the value value of of aa y

y = = % % variable, variable, enter enter just just its'its'

% name % name 3.1337

3.1337 >>

>> theta=acos(‐1theta=acos(‐1) ) % % Assign Assign arccos(‐1) arccos(‐1) to to thetatheta % Matlab uses radian for all % Matlab uses radian for all theta

theta = = % % trig trig functionsfunctions

3.1416 3.1416 >>

>> theta‐pi theta‐pi % % Note Note that that pi pi is is built built intointo % Matlab, and more precision % Matlab, and more precision ans

ans = = % % is is kept kept internally internally than than isis

% printed on the screen % printed on the screen 0

0

Creating and Working With Matrices

Creating and Working With Matrices

In Matlab, there are a number of ways to create matrices. First, let's look at how to generate vectors (call them In Matlab, there are a number of ways to create matrices. First, let's look at how to generate vectors (call themxx

and

and yy), which are 1xN matrices. We will make), which are 1xN matrices. We will makexx go from 0 to 3*pi. go from 0 to 3*pi.

>>

>> x=0:0.1:3*pi; x=0:0.1:3*pi; % % Create Create vector vector x x from from 0 0 to to 3*pi 3*pi inin % increments of 0.1

% increments of 0.1 % But, could also use: % But, could also use: >>

>> x x = = linspace(0,3*plinspace(0,3*pi,100); i,100); % % Create Create vector vector x x from from 0 0 to to 3*pi 3*pi withwith % 100 steps exactly

% 100 steps exactly >>

>> beta=0.5; beta=0.5; % % Create Create constant constant beta beta for for error error functionfunction >>

>> y=beta*erf(x/y=beta*erf(x/5); 5); % % Compute Compute erf() erf() for for each each x x value, value, andand % assign to a y value

% assign to a y value

% Note that there is no loop here, but % Note that there is no loop here, but % y now has as many entries as x! % y now has as many entries as x! >>

>> plot(x,y) plot(x,y) % % Plot Plot x x vs. vs. y y with with a a lineline

The plot should look something like this. The plot should look something like this.

 Now, let's

(4)

>>

>> x x = = [1 [1 4 4 7; 7; 2 2 5 5 8; 8; 3 3 6 6 9]; 9]; % % semicolons semicolons denote denote changes changes ofof % row

% row >>

>> x x = = [1,4,7 [1,4,7 % % Matlab's Matlab's command command line line knowsknows 2,5,8

2,5,8 % % the the matrix matrix is is not not finishedfinished

3,6,9];

3,6,9]; % % until until the the closing closing ']'']'

In any case, the result is the same, the following 3 x 3 matrix stored as the variable In any case, the result is the same, the following 3 x 3 matrix stored as the variablexx::

>>

>> x x % % Display Display the the current current value value of of xx x x == 1 4 7 1 4 7 2 5 8 2 5 8 3 6 9 3 6 9

You should notice that square brackets (

You should notice that square brackets ([ [ ]]) enclose the matrix, spaces or commas () enclose the matrix, spaces or commas (,,) denote elements within a) denote elements within a row, and either a semicolon (

row, and either a semicolon (;;) or a hard return denote rows.) or a hard return denote rows.

Matlab also has functions to produce matrices of zeros and ones of a specified size: Matlab also has functions to produce matrices of zeros and ones of a specified size:

>>

>> zeros([3 zeros([3 3]) 3]) % % Produce Produce matrix matrix of of all all zeros,zeros, % size of 3x3 % size of 3x3 ans = ans = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 >>

>> zeros(3, zeros(3, 3) 3) % % Alternate Alternate size size format format of of aboveabove ans = ans = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 >>

>> zeros(2) zeros(2) % % Matrix Matrix of of zeros, zeros, size size 2x22x2 ans = ans = 0 0 00 0 0 00 >>

>> zeros([1 zeros([1 2]) 2]) % % Row Row vector vector of of zeros, zeros, 2 2 longlong ans =

ans = 0

0 00

>>

>> zeros([2 zeros([2 1]) 1]) % % Column Column vector vector of of zeros, zeros, 2 2 longlong ans = ans = 0 0 0 0 >>

>> ones(2, ones(2, 2) 2) % % Same Same as as zeros(), zeros(), but but matrix matrix filled filled with with 11 ans =

ans = 1

(5)

1

1 11

To access matrix elements, specify the rows and columns we are interested in. Remember how we used the To access matrix elements, specify the rows and columns we are interested in. Remember how we used the colon (

colon (::) to fill in numbers when we plotted numbers from 1 to 5 in the first section? We will use that again. The) to fill in numbers when we plotted numbers from 1 to 5 in the first section? We will use that again. The

syntax is

syntax is x(row,col)x(row,col) so, for example, if we want the to assign the element in the third row, first column to the so, for example, if we want the to assign the element in the third row, first column to the variable

variable yy, we type:, we type:

>>

>> y y = = x(3,1); x(3,1); % % Assign Assign row row 3, 3, col col 1 1 element element of of x x to to yy

To specify an entire row or column, use a colon (

To specify an entire row or column, use a colon (::) in place of the row or column number. So, if we want the) in place of the row or column number. So, if we want the entire second column, we would type:

entire second column, we would type:

>>

>> y y = = x(:,2); x(:,2); % % Assign Assign all all rows, rows, col col 2 2 elements elements to to yy

 Now

 Now let's try let's try a a short exshort exercise to ercise to use use matrices amatrices and nd matrix matrix operations.operations. 1. Create a vector of the integers from 1 to 5 and name it

1. Create a vector of the integers from 1 to 5 and name itaa.. 2. Add 1 to all the elements of

2. Add 1 to all the elements ofaa, and store in, and store in aa..

3. Create a vector of the integers from 5 to 1 and name it 3. Create a vector of the integers from 5 to 1 and name itbb.. 4. Add

4. Addaa totobb and store the result in and store the result incc..

Here is a transcript (diary) of a matlab session implementing the exercise: Here is a transcript (diary) of a matlab session implementing the exercise:

>>

>> a=1:5; a=1:5; % % vector vector of of 1 1 to to 5, 5, increment increment 11 >>

>> a=a+1 a=a+1 % % add add 1 1 to to all all elements elements of of aa a

a ==

2 3 4 5 6

2 3 4 5 6

>>

>> b=5:‐1:1 b=5:‐1:1 % % vector vector of of 5 5 to to 1, 1, increment increment ‐1‐1 b

b ==

5 4 3 2 1

5 4 3 2 1

>>

>> c=a+b c=a+b % % add add a a and and b, b, store store in in cc c

c ==

7 7 7 7 7

7 7 7 7 7

 Note

 Note that that all vall vectors used ectors used so far so far have have beenbeenrow vectorsrow vectors; the vector is a row from a matrix (one row, many; the vector is a row from a matrix (one row, many

columns). There are also column vectors, which are displayed vertically (many rows, one column). To transform columns). There are also column vectors, which are displayed vertically (many rows, one column). To transform a row vector to a column vector (or back), use the

a row vector to a column vector (or back), use thetransposetranspose operation; in Matlab, this is denoted by operation; in Matlab, this is denoted by'' after the after the vector (or matrix) name.

vector (or matrix) name.

>> a' >> a' ans = ans = 2 2 3 3 4 4 5 5 6 6

Matlab, being focused on matrix operations, always assumes operations are matrix operations unless told Matlab, being focused on matrix operations, always assumes operations are matrix operations unless told otherwise. In the exercise above, we added a scalar to a matrix, which is the same as adding a scalar to every otherwise. In the exercise above, we added a scalar to a matrix, which is the same as adding a scalar to every

(6)

element of the matrix. In general, though, Matlab will do matrix addition, multiplication, division, etc. element of the matrix. In general, though, Matlab will do matrix addition, multiplication, division, etc. To make Matlab apply an operation to each element individually (rather than use matrix operations), use a To make Matlab apply an operation to each element individually (rather than use matrix operations), use a ..

(period) before the operator; for example, to square each element of a vector, we use: (period) before the operator; for example, to square each element of a vector, we use:

>> a=1:5; >> a=1:5; >>

>> a.*a a.*a % % the the . . makes makes Matlab Matlab apply apply the the ** % to each element as a set of scalar % to each element as a set of scalar ans

ans = = % % operations, operations, NOT NOT matrix matrix multiplicatiomultiplicationn 1

1 4 4 9 9 16 16 2525

If there is no

If there is no .., Matlab assumes the intent is a matrix operation, which won't work for two row vectors:, Matlab assumes the intent is a matrix operation, which won't work for two row vectors:

>> a*a >> a*a

??? Error using ==> * ??? Error using ==> *

Inner matrix dimensions must agree. Inner matrix dimensions must agree.

If the intent really is to do a matrix multiplication of

If the intent really is to do a matrix multiplication of aa bybyaa, we need to take the transpose of the second vector:, we need to take the transpose of the second vector:

>> a*a' >> a*a' ans = ans = 55 55 Since

Since aa is a 1x5 vector, is a 1x5 vector,a'a' (transpose of (transpose ofaa) is a 5x1 vector. When multiplied, the result is a 1x1 vector, which is a) is a 5x1 vector. When multiplied, the result is a 1x1 vector, which is a scalar, as seen here.

scalar, as seen here.

Keeping track of matrix dimensions can be difficult, but is extremely important. Fortunately, Matlab will Keeping track of matrix dimensions can be difficult, but is extremely important. Fortunately, Matlab will normally produce errors when your code tries to do something mathematically incorrect.

normally produce errors when your code tries to do something mathematically incorrect.

Advanced Matrix Indexing - skip and come back if desired

Advanced Matrix Indexing - skip and come back if desired

Matlab has a very general indexing ability, which can make code that is compact and efficient, but less Matlab has a very general indexing ability, which can make code that is compact and efficient, but less

transparent. In general, anywhere you can index a matrix with a single number (or set of numbers), you can also transparent. In general, anywhere you can index a matrix with a single number (or set of numbers), you can also index with a vector or matrix. Some examples:

index with a vector or matrix. Some examples:

EDU>>

EDU>> a=[1:3; a=[1:3; 4:6; 4:6; 7:9] 7:9] % % Create Create 3x3 3x3 matrixmatrix a a == 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9 EDU>>

EDU>> a(:) a(:) % % Access Access matrix matrix as as a a vector.vector.

% Note that the elements are taken % Note that the elements are taken ans

ans = = % % from from each each column column first, first, then then eacheach % row.

% row. This fThis format ormat allows allows the trethe treatmentatment 1

1 % % of of any any multi‐dimensiomulti‐dimensional nal array array as as aa 4

4 % % vector, vector, which which can can be be useful useful for for somesome 7

7 % % function function calls.calls.

2

2 % % 3+ 3+ dimensional dimensional arrays arrays will will take take elementselements 5

5 % % first first from from the the last last dimension, dimension, workingworking 8

8 % % back back to to the the first first dimension!dimension! 3 3 6 6 9 9 EDU>> b=[1:10].^2 EDU>> b=[1:10].^2

(7)

b b ==

1

1 4 4 9 9 16 16 25 25 36 36 49 49 64 64 81 81 100100 EDU>>

EDU>> b(a) b(a) % % Access Access elements elements of of b b using using values values of of a.a. % Note that the result is a matrix with the % Note that the result is a matrix with the ans

ans = = % % same same shape shape as as a, a, but but with with values values taken taken fromfrom % b; the entries of a are used as indexes % b; the entries of a are used as indexes 1

1 4 4 9 9 % % into into the the vector vector b. b. Matlab Matlab will will produce produce anan 16

16 25 25 36 36 % % error error if if any any index index from from a a is is outside outside thethe 49

49 64 64 81 81 % % bounds bounds of of b.b. EDU>>

EDU>> a a % % Reminder Reminder of of entries entries of of matrix matrix aa a a == 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9 EDU>> b=flipud(a) EDU>> b=flipud(a) b b == 7 8 9 7 8 9 4 5 6 4 5 6 1 2 3 1 2 3 EDU>>

EDU>> b(a) b(a) % % Access Access elements elements of of b b using using values values of of a.a. % Note that the elements were taken in % Note that the elements were taken in ans

ans = = % % column‐order column‐order (elements (elements 1‐3 1‐3 are are the the firstfirst % colum

% column). n). This cThis comes fromes from Matlom Matlab treab treatingating 7

7 4 4 1 1 % % b b as as a a vector vector for for the the indexing indexing operation,operation, 8

8 5 5 2 2 % % with with the the resulting resulting vector vector reshaped reshaped to to thethe 9

9 6 6 3 3 % % size size of of a.a.

These examples are all designed to show how Matlab stores and retrieves information in arrays. Matlab stores These examples are all designed to show how Matlab stores and retrieves information in arrays. Matlab stores all arrays as a long vector in memory, regardless of the number of dimensions. A multi-dimensional array (a all arrays as a long vector in memory, regardless of the number of dimensions. A multi-dimensional array (a matrix) is stored as a vector, with additional information on how many rows and columns are in the matrix, so matrix) is stored as a vector, with additional information on how many rows and columns are in the matrix, so Matlab can quickly access any element using (row, column) indexing. The translation for a 2-D matrix (nr x nc Matlab can quickly access any element using (row, column) indexing. The translation for a 2-D matrix (nr x nc elements) is simple:

elements) is simple:

A(i,j) == A(j*nr + i) A(i,j) == A(j*nr + i)

where nr is the number of rows in the matrix. A 3-D array (n1 x n2 x n3 elements) is similar: where nr is the number of rows in the matrix. A 3-D array (n1 x n2 x n3 elements) is similar:

A(i,j,k) == A((k*n1*n2) + (j*n2) + i) A(i,j,k) == A((k*n1*n2) + (j*n2) + i)

where n1 is the

where n1 is the stride stride for the last dimension, and n2 is the stride for the second dimension. for the last dimension, and n2 is the stride for the second dimension.

Given this memory layout for a multi-dimensional matrix, it is clear why accessing the matrix as a vector (using Given this memory layout for a multi-dimensional matrix, it is clear why accessing the matrix as a vector (using the

the A(:)A(:) notation) results in a vector with columns attached end-to-end; Matlab is starting at the first element notation) results in a vector with columns attached end-to-end; Matlab is starting at the first element and reading straight through until the end. This sort of indexing, once understood, can make some very efficient and reading straight through until the end. This sort of indexing, once understood, can make some very efficient algorithms. For example, translating gray scale values in an image from one scale to another:

algorithms. For example, translating gray scale values in an image from one scale to another:

EDU>>

EDU>> A A = = floor(rand(10floor(rand(10)*255) )*255) % % Create Create random random 10x10 10x10 matrixmatrix % of 8‐bit gray scale values % of 8‐bit gray scale values A A = = % % [0‐255].[0‐255]. 3 3 67 67 137 137 173 173 18 18 211 211 192 192 118 118 46 46 66 73 73 192 192 158 158 18 18 49 49 233 233 169 169 233 233 127 127 221221

(8)

208 208 168 168 174 174 18 18 96 96 28 28 225 225 58 58 107 107 66 251 251 54 54 172 172 3 3 70 70 207 207 69 69 219 219 168 168 132132 4 4 153 153 223 223 57 57 196 196 231 231 106 106 167 167 171 171 4949 208 208 154 154 3 3 131 131 80 80 39 39 54 54 227 227 244 244 182182 158 158 168 168 79 79 116 116 162 162 31 31 9 9 124 124 48 48 6363 142 142 46 46 198 198 179 179 251 251 194 194 20 20 253 253 28 28 238238 62 62 162 162 78 78 148 148 128 128 184 184 216 216 95 95 144 144 3434 209 209 43 43 236 236 129 129 241 241 166 166 86 86 135 135 247 247 133133 EDU>> B = [0:2:100 linspace(101,199,256‐80) 200:2:256]; size(B) EDU>> B = [0:2:100 linspace(101,199,256‐80) 200:2:256]; size(B) % Create new gray scale mapping % Create new gray scale mapping ans

ans = = % % that that compresses compresses the the ends ends andand % expands the middle of the % expands the middle of the 1

1 256 256 % % spectrum; spectrum; must must be be 256 256 entries!entries! EDU>>

EDU>> floor(B(A+1)) floor(B(A+1)) % % Remap Remap A A by by choosing choosing entries entries ofof % the new map (B) accoding to values % the new map (B) accoding to values ans

ans = = % % in in A. A. Note Note the the addition addition of of 1, 1, toto % shift [0‐255] to [1‐256]. % shift [0‐255] to [1‐256]. 4 4 109 109 148 148 168 168 34 34 190 190 179 179 137 137 90 90 1010 112 112 179 179 160 160 34 34 96 96 210 210 166 166 210 210 143 143 195195 188 188 165 165 169 169 34 34 125 125 54 54 197 197 104 104 131 131 1010 246 246 102 102 168 168 4 4 111 111 187 187 110 110 194 194 165 165 145145 6 157 6 157 196 196 103 103 181 181 206 206 131 131 165 165 167 167 9696 188 188 158 158 4 4 145 145 116 116 76 76 102 102 199 199 232 232 173173 160 160 165 165 116 116 136 136 162 162 60 60 16 16 141 141 94 94 107107 151 151 90 90 182 182 172 172 246 246 180 180 38 38 250 250 54 54 220220 106 162 106 162 115 115 154 154 143 143 174 174 192 192 125 125 152 152 6666 188 188 84 84 216 216 144 144 226 226 164 164 120 120 147 147 238 238 146146

This efficient, but less transparent, implementation of a remapping could also be done via

This efficient, but less transparent, implementation of a remapping could also be done viaforfor loops (one or two, loops (one or two,

depending on implementation), but that would be much, much slower for large matrices. depending on implementation), but that would be much, much slower for large matrices.

Loading and Saving Data

Loading and Saving Data

The key to loading data into Matlab is to remember that Matlab only uses matrices. That means that if you want The key to loading data into Matlab is to remember that Matlab only uses matrices. That means that if you want to easily read a data set into Matlab, all of the rows must have the same number of elements, and they must all to easily read a data set into Matlab, all of the rows must have the same number of elements, and they must all  be

 be numbers.numbers.

Most commonly, you'll be dealing with a text (ASCII) file. If you have a set of data on disk in a file called Most commonly, you'll be dealing with a text (ASCII) file. If you have a set of data on disk in a file called  points.dat 

 points.dat , then to load it, you would type:, then to load it, you would type:

>> load points.dat >> load points.dat

This will load your data into the Matlab variable

This will load your data into the Matlab variablepointspoints. Let's assume that the file. Let's assume that the file points.datpoints.dat contains two contains two columns, where column 1 is height and column 2 is distance. To break apart

columns, where column 1 is height and column 2 is distance. To break apart pointspoints into something more into something more meaningful, we use: meaningful, we use: >> height = points(:,1); >> height = points(:,1); >> distance = points(:,2); >> distance = points(:,2);

This creates a vector

This creates a vectorheightheight from the first column (all rows), and from the first column (all rows), anddistancedistance from the second column. from the second column. To save the same data into an ASCII file called

To save the same data into an ASCII file called mydata.dat mydata.dat , we use either:, we use either:

>>

>> save save mydata.dat mydata.dat height height distance distance ‐ascii ‐ascii % % common common form form forfor % command line % command line

or  or 

(9)

>> save('mydata.dat', 'height', 'distance', '‐ascii'); >> save('mydata.dat', 'height', 'distance', '‐ascii');

% common form for % common form for % use in scripts and % use in scripts and % functions

% functions

The

The ‐ascii‐ascii flag is important here; it tells Matlab to make the file in ASCII text, not a platform-independant flag is important here; it tells Matlab to make the file in ASCII text, not a platform-independant  binary

 binary file. Without file. Without the the flag, flag, the the file file would would be be unreadable unreadable with with standard standard editors. Text editors. Text is the is the most pmost portable ortable andand editable format, but is larger on disk. Matlab's binary format is compatible across all platforms of Matlab editable format, but is larger on disk. Matlab's binary format is compatible across all platforms of Matlab (Windows, UNIX, Mac, etc.), and is more compact than text, but cannot be edited outside of Matlab. (Windows, UNIX, Mac, etc.), and is more compact than text, but cannot be edited outside of Matlab.

You will note that when Matlab saves files in ASCII format, it uses scientific notation whether it needs it or not. You will note that when Matlab saves files in ASCII format, it uses scientific notation whether it needs it or not. More powerful and flexible save and load schemes exist in Matlab; they use the fprintf() and fscanf() functions More powerful and flexible save and load schemes exist in Matlab; they use the fprintf() and fscanf() functions along with fopen() to control file output. A discussion of the intricacies of using fscanf/fprintf is beyond this along with fopen() to control file output. A discussion of the intricacies of using fscanf/fprintf is beyond this tutorial; see the help pages or someone with firsthand experience.

tutorial; see the help pages or someone with firsthand experience.

Plotting

Plotting

 Now

 Now that that we we can can save, save, load, load, and and create create data, data, we we need need a a way way to to plot plot it. it. The The main main function function for mafor making king 2- 2-dimensional plots is called

dimensional plots is called plotplot. To create a plot of two vectors. To create a plot of two vectorsxx and andyy, type, typeplot(x,y)plot(x,y). With only one argument. With only one argument ((plot(x)plot(x)))plotplot will plot the argument will plot the argumentxx as a function of its index. If as a function of its index. Ifxx is a matrix, is a matrix,plotplot will produce a plot of the will produce a plot of the columns of

columns of xx each in a different color or linestyle. More detail on the basic use of plot is available via the each in a different color or linestyle. More detail on the basic use of plot is available via thehelphelp plot

plot command in Matlab. command in Matlab.

That brings us to the third possible argument for

That brings us to the third possible argument for plotplot, the linestyle., the linestyle.plot(x,y,s)plot(x,y,s) will plot will plotyy as a function of as a function ofxx

using linestyle

using linestyless, where, wheress is a 1 to 3 character string (enclosed by single quotes) made up of the following is a 1 to 3 character string (enclosed by single quotes) made up of the following

characters. characters.

y

y yellow yellow . . pointpoint m

m magenta magenta o o circlecircle c

c cyan cyan x x x‐markx‐mark r

r red red + + plusplus g

g green green ‐ ‐ solidsolid b

b blue blue * * starstar w

w white white : : dotteddotted k

k black black ‐. ‐. dashdotdashdot ‐‐ dashed ‐‐ dashed

For example, to create a plot of x versus y, using magenta circles, type the command

For example, to create a plot of x versus y, using magenta circles, type the commandplot(x,y,'mo');plot(x,y,'mo');. To plot. To plot more than one line, you can combine plots by typing

more than one line, you can combine plots by typingplot(x1,y1,s1,x2,y2,s2,...);plot(x1,y1,s1,x2,y2,s2,...);..

As an example, plot a random vector (10 x 1) and an integer vector from 1 to 10 using two different line types: As an example, plot a random vector (10 x 1) and an integer vector from 1 to 10 using two different line types:

>> y1=rand(10,1); >> y1=rand(10,1); >> y2 = linspace(1,0,10); >> y2 = linspace(1,0,10); >> x = 1:10; >> x = 1:10;

>> plot(x, y1, 'g+', x, y2, 'r‐'); >> plot(x, y1, 'g+', x, y2, 'r‐'); >> title('Test of linetype strings'); >> title('Test of linetype strings'); >> xlabel('X Axis');

>> xlabel('X Axis'); >> ylabel('Y Axis'); >> ylabel('Y Axis');

The plot should look something like this: The plot should look something like this:

(10)

Another useful plotting command is called errorbar. The following example will generate a plot of the random Another useful plotting command is called errorbar. The following example will generate a plot of the random vector y1 using an error of 0.1 above and below the line:

vector y1 using an error of 0.1 above and below the line:

>> errorbar(x,y1,ones(size(y1)).*0.1,'r‐') >> errorbar(x,y1,ones(size(y1)).*0.1,'r‐') >> title('Test of errorbar');

>> title('Test of errorbar');

>> xlabel('X Axis'); ylabel('Y Axis'); >> xlabel('X Axis'); ylabel('Y Axis');

The plot should now look something like this: The plot should now look something like this:

(11)

Labelling the Plot

Labelling the Plot

title

title,, xlabelxlabel, and, andylabelylabel create labels for the top and sides of the plot. They each take a string variable, which create labels for the top and sides of the plot. They each take a string variable, which must be in single quotes. One other labelling function that might be useful is the

must be in single quotes. One other labelling function that might be useful is thetexttext function. The command function. The command

text(1,10,'Here is some text');

text(1,10,'Here is some text'); will write the text string will write the text string'Here is some text''Here is some text' at the (x,y) position (1,10) in at the (x,y) position (1,10) in data units.

data units.

Changing the Axes

Changing the Axes

One thing you might want to do with your plot is to change the axes. Normally, Matlab automatically chooses One thing you might want to do with your plot is to change the axes. Normally, Matlab automatically chooses appropriate axes for you, but they're easy to change. The

appropriate axes for you, but they're easy to change. Theaxisaxis command will allow you to find out the current command will allow you to find out the current axes and change them.

axes and change them.

>>

>> axis axis % % Get Get the the current current axisaxis

% settings % settings ans = ans = 0 0 12.0000 12.0000 ‐0.2000 ‐0.2000 1.40001.4000 >>

>> axis([2 axis([2 10 10 ‐0.2 ‐0.2 1.0]) 1.0]) % % Reset Reset axes axes extents extents toto % [xmin xmax ymin ymax] % [xmin xmax ymin ymax]

Sometimes you will want to switch the position of the plot origin (normally used for plotting images of  Sometimes you will want to switch the position of the plot origin (normally used for plotting images of  matrices). Typing

matrices). Typing

>> axis('ij') >> axis('ij')

will switch the Y axis direction so that (0,0) is to the upper right. will switch the Y axis direction so that (0,0) is to the upper right.

(12)

Appending Data to Plots

Appending Data to Plots

Sometimes it's useful to be able to add something to a plot window without having to draw two lines with the Sometimes it's useful to be able to add something to a plot window without having to draw two lines with the same

sameplotplot statement (as we did above). So Matlab has a command, statement (as we did above). So Matlab has a command,holdhold which will cause the plot to remain (it which will cause the plot to remain (it

doesn't redraw it). Typing

doesn't redraw it). Typinghold onhold on will hold the current plot, and will hold the current plot, andhold offhold off will release the plot. Also, will release the plot. Also,holdhold byby itself will toggle the hold state. You might also want to use

itself will toggle the hold state. You might also want to useclfclf to clear the graphics window and release the to clear the graphics window and release the window.

window.

Using Graphics Handles in Matlab

Using Graphics Handles in Matlab

For those of you that will use Matlab to make plots for publications and presentations will greatly benefit from a For those of you that will use Matlab to make plots for publications and presentations will greatly benefit from a few useful but poorly documented Matlab functions. The commands

few useful but poorly documented Matlab functions. The commandsgetget and andsetset allow the user to check or  allow the user to check or  tweak a plot into more pleasing form. For example by using these commands, one can change font sizes, colors, tweak a plot into more pleasing form. For example by using these commands, one can change font sizes, colors, line widths and axes labels as well as many other plot attributes.

line widths and axes labels as well as many other plot attributes. We will start by generating a simple plot:

We will start by generating a simple plot:

>> x = [0:100]*pi/50; >> x = [0:100]*pi/50; >> y = sin(x);

>> y = sin(x);

All the attributes of a plot are stored in a data structure which may be obtained by typing: All the attributes of a plot are stored in a data structure which may be obtained by typing:

>> p = plot(x,y) >> p = plot(x,y)

By giving a plot an output varible, you have obtained the object handles. In order to find out what handles exist By giving a plot an output varible, you have obtained the object handles. In order to find out what handles exist we use the

we use the getget command. command.

>> get(p) >> get(p)

A list will be printed out which is partially listed below: A list will be printed out which is partially listed below:

Color Color = = [0 [0 0 0 1]1] EraseMode = normal EraseMode = normal LineStyle = ‐ LineStyle = ‐ LineWidth = [0.5] LineWidth = [0.5] ... ...

If you wish to obtain the value to just one axis handle, for example the line style, this can be done by typing: If you wish to obtain the value to just one axis handle, for example the line style, this can be done by typing:

>> get(p,'LineStyle') >> get(p,'LineStyle') ans = ans = ‐ ‐

Each of these is a graphic handles that may be changed by using the command

Each of these is a graphic handles that may be changed by using the commandsetset. For example, suppose that. For example, suppose that we now wish to make the plot red instead of blue and increase the line width from 0.5 to 1.

we now wish to make the plot red instead of blue and increase the line width from 0.5 to 1.

>> set(p,'Color',[1 0 0],'LineWidth',1); >> set(p,'Color',[1 0 0],'LineWidth',1);

Any graphic handle may be changed using this method. As you begin to use Matlab, these commands may not Any graphic handle may be changed using this method. As you begin to use Matlab, these commands may not  be

 be used used often, often, but but as as you you become become more more proficient, yoproficient, you u may may find thefind these se commands commands to to be be invaluable. invaluable. Other Other  attributes of a plot can be changed by using

attributes of a plot can be changed by usinggcagca (for axes properties) and (for axes properties) andgcfgcf (for figure window properties). (for figure window properties).

Type

Typeget(gca)get(gca) and andget(gcf)get(gcf) to see what other attributes may be changed. And like any other part of Matlab, to see what other attributes may be changed. And like any other part of Matlab,

these commands may be added to scripts to created custom plots. these commands may be added to scripts to created custom plots.

Creating m-files

Creating m-files

(13)

In Matlab, you can create a file using Matlab commands, called an

In Matlab, you can create a file using Matlab commands, called anm-filem-file. The file needs to have a. The file needs to have a .m.m extension extension (hence the name -- m-file). There are two types of m-files: (1) scripts and (2) functions. We will start with

(hence the name -- m-file). There are two types of m-files: (1) scripts and (2) functions. We will start with scripts, as they are easier to write.

scripts, as they are easier to write.

Matlab Scripts

Matlab Scripts

Running a Matlab script is the same as typing the commands in the workspace. Any variables created or changed Running a Matlab script is the same as typing the commands in the workspace. Any variables created or changed in the script are changed in the workspace. A script file is executed by typing the name of the script (without the in the script are changed in the workspace. A script file is executed by typing the name of the script (without the .m

.m extension). Script files do not take or return any arguments, they only operate on the variables in the extension). Script files do not take or return any arguments, they only operate on the variables in the

workspace. If you need to be able to specify an argument, then you need to use a function. Here is an example of  workspace. If you need to be able to specify an argument, then you need to use a function. Here is an example of  a simple script to plot a function:

a simple script to plot a function:

% makefunction.m % makefunction.m

% script to plot erfc in domain [0,pi] % script to plot erfc in domain [0,pi] x

x = = linspace(0,plinspace(0,pi,25); i,25); % % Create Create x x from from 0 0 to to pi pi with with 25 25 valuesvalues y

y = = erfc(x); erfc(x); % % Calc. Calc. erfc erfc of of xx scl

scl = = 0.25; 0.25; % % Plotting Plotting scaling scaling factorfactor y = y*scl;

y = y*scl; plot(x,y,

plot(x,y, 'r‐'); 'r‐'); % % Plot Plot x x and and yy title('My

title('My Script'); Script'); % % Create Create a a titletitle xlabel('X');

xlabel('X'); % % Label Label the the x x and and y y axesaxes ylabel('Y');

ylabel('Y');

 Note

 Note the the use use of of '%' '%' characters characters to to introduce introduce comments, comments, just as just as in in the the examples examples throughout throughout this tutorial. this tutorial. In In general,general, Matlab treats anything after a '%' as if it wasn't there; comments are silently ignored. This can be very useful Matlab treats anything after a '%' as if it wasn't there; comments are silently ignored. This can be very useful when writing m-files, as debugging commands can be commented out after the m-file is tested.

when writing m-files, as debugging commands can be commented out after the m-file is tested.

Running this m-file produces the following variables in the workspace and plot (in a separate window): Running this m-file produces the following variables in the workspace and plot (in a separate window):

>>

>> whos whos % % Empty Empty workspace; workspace; no no variables variables defineddefined >>

>> makefunction makefunction % % Create Create vars, vars, plotplot >>

>> whos whos % % List List vars vars in in workspaceworkspace Name

Name Size Size Bytes Bytes ClassClass scl

scl 1x1 1x1 8 8 double double arrayarray

x

x 1x25 1x25 200 200 double double arrayarray y

y 1x25 1x25 200 200 double double arrayarray Grand total is 51 elements using 408 bytes Grand total is 51 elements using 408 bytes

(14)

You should notice that all of the variables used in the script are now sitting in the workspace, so that they can be You should notice that all of the variables used in the script are now sitting in the workspace, so that they can be used again. This is exactly the same as if they had been typed in separately. Anytime a computation is going to used again. This is exactly the same as if they had been typed in separately. Anytime a computation is going to take more than a single line, it is worthwhile to create a throwaway m-file; the file can be saved, edited, and take more than a single line, it is worthwhile to create a throwaway m-file; the file can be saved, edited, and revised much easier than using just the command line.

revised much easier than using just the command line.

Matlab Functions

Matlab Functions

Matlab functions are very similar to scripts, but they can accept and return values as

Matlab functions are very similar to scripts, but they can accept and return values as argumentsarguments. Most of the. Most of the commands available in Matlab are actually pre-written Matlab functions; only a small number of important commands available in Matlab are actually pre-written Matlab functions; only a small number of important functions are compiled into the program (e.g. matrix multiply).

functions are compiled into the program (e.g. matrix multiply).

To write a function, create an m-file with a function declaration as the first line (see the example, below). The To write a function, create an m-file with a function declaration as the first line (see the example, below). The return values in the declaration will need to be set somewhere in the function body; whatever value these return values in the declaration will need to be set somewhere in the function body; whatever value these variables have at the end of the function will be returned.

variables have at the end of the function will be returned.

Comments immediately after the function declaration will be used as the

Comments immediately after the function declaration will be used as thehelphelp page for the function; it should page for the function; it should have useful information on function arguments and return values. If the function uses a special (named)

have useful information on function arguments and return values. If the function uses a special (named) algorithm, that is useful to put in the help as well.

algorithm, that is useful to put in the help as well. Functions keep variables

Functions keep variables local local ; variables defined in the function are not part of the workspace, and the function; variables defined in the function are not part of the workspace, and the function cannot access variables in the workspace unless they are passed as arguments. Hence, functions can define a cannot access variables in the workspace unless they are passed as arguments. Hence, functions can define a variable without worrying if it already exists. All variables in a function are lost once the function completes. variable without worrying if it already exists. All variables in a function are lost once the function completes. An example function definition (from a file named llsqErr.m):

An example function definition (from a file named llsqErr.m):

function [mean, sigma] = llsqErr(x, y, N, dx, dy); function [mean, sigma] = llsqErr(x, y, N, dx, dy); % function [mean, sigma] = llsqErr(x, y, N, dx, dy); % function [mean, sigma] = llsqErr(x, y, N, dx, dy);

(15)

% %

% Generat

% Generate mean e mean and s.d. and s.d. of slope of slope and inteand interceptrcept

% for linear least‐squares fit to x, y data set, using MC % for linear least‐squares fit to x, y data set, using MC % technique

% technique with random with random errors of errors of scale dx, scale dx, dy. dy. Random errRandom errorsors % are uniformly distributed, and symmetric (with scale dx, dy) % are uniformly distributed, and symmetric (with scale dx, dy) % about x and y values.

% about x and y values. %

%

% x, y are vectors of data, of length > 2 % x, y are vectors of data, of length > 2 % dx, dy are scalars

% dx, dy are scalars

% N is scalar (# of trials); typically should be >1e3 % N is scalar (# of trials); typically should be >1e3 %

%

% Uses N trials with random perturbations computed for each trial % Uses N trials with random perturbations computed for each trial %

%

% Returns values as [slope intercept] for means and s.d.s % Returns values as [slope intercept] for means and s.d.s %% Notes %%

%% Notes %%

% This code really ought to guarantee that the randomly generated % This code really ought to guarantee that the randomly generated % pertrubati

% pertrubations are uons are unique. nique. This is This is assumed froassumed from the use m the use of aof a % pseudo‐random number generator, and the likely event that N is % pseudo‐random number generator, and the likely event that N is % less than the recurrence interval of the PRNG.

% less than the recurrence interval of the PRNG. %

%

% It appears necessary to compute the predicted errors for each % It appears necessary to compute the predicted errors for each % data set individually; attempts to generate a general correlation % data set individually; attempts to generate a general correlation % plot didn't pan out.

% plot didn't pan out. m = zeros(N, 2);

m = zeros(N, 2); for i=1:N

for i=1:N

xh = x + dx*(2*rand(size(x))‐1); % generate perturbed x, y vecs xh = x + dx*(2*rand(size(x))‐1); % generate perturbed x, y vecs yh = y + dy*(2*rand(size(y))‐1);

yh = y + dy*(2*rand(size(y))‐1); p =

p = polyfit(xh, polyfit(xh, yh, 1); yh, 1); % get % get slope, inslope, intercepttercept m(i, :) = p; % store

m(i, :) = p; % store end

end mean

mean = [ = [ mean(m(:,1)) mean(m(:,1)) mean(m(:,2)) mean(m(:,2)) ];]; sigma

sigma = [ = [ std(m(:,1)) std(m(:,1)) std(m(:,2)) std(m(:,2)) ];];

This function accepts 5 arguments:

This function accepts 5 arguments:xx,,yy,,NN,,dxdx, and, anddydy. It returns two vectors:. It returns two vectors: meanmean and andsigmasigma. Note that the. Note that the

comments after the function declaration indicate what the arguments and return values are, as well as how the comments after the function declaration indicate what the arguments and return values are, as well as how the function does its' work. Also note that there are comments about possible problems with this algorithm and function does its' work. Also note that there are comments about possible problems with this algorithm and implementation. A user looking at the source code for this function can determine what is happening, and what implementation. A user looking at the source code for this function can determine what is happening, and what might need to be changed. Also note that the function uses simple variable names, which could exist in the might need to be changed. Also note that the function uses simple variable names, which could exist in the workspace (

workspace (xx,,yy, etc.); because this is a function, the variables used are not part of the workspace, so there are no, etc.); because this is a function, the variables used are not part of the workspace, so there are no concerns.

concerns.

When a user gets help for this function, the first set of comments (up to the blank line) is returned as the help When a user gets help for this function, the first set of comments (up to the blank line) is returned as the help  page:

 page:

>> help llsqErr >> help llsqErr

function [mean, sigma] = llsqErr(x, y, N, dx, dy); function [mean, sigma] = llsqErr(x, y, N, dx, dy); Generate

Generate mean and mean and s.d. of s.d. of slope slope and inteand interceptrcept

for linear least‐squares fit to x, y data set, using MC for linear least‐squares fit to x, y data set, using MC technique

technique with random with random errors of errors of scale dx, scale dx, dy. dy. Random errRandom errorsors are uniformly distributed, and symmetric (with scale dx, dy) are uniformly distributed, and symmetric (with scale dx, dy) about x and y values.

about x and y values.

x, y are vectors of data, of length > 2 x, y are vectors of data, of length > 2 dx, dy are scalars

dx, dy are scalars

N is scalar (# of trials); typically should be >1e3 N is scalar (# of trials); typically should be >1e3

Uses N trials with random perturbations computed for each trial Uses N trials with random perturbations computed for each trial

(16)

Returns values as [slope intercept] for means and s.d.s Returns values as [slope intercept] for means and s.d.s

Saving Your Session

Saving Your Session

One other useful command is the

One other useful command is thediarydiary command. Typing command. Typing >> diary filename.txt

>> diary filename.txt

will create a file with all the commands you've typed. When you're done, typing will create a file with all the commands you've typed. When you're done, typing

>> diary off >> diary off

will close the file. This might be useful to create a record of your work to hand in with a lab or to create the will close the file. This might be useful to create a record of your work to hand in with a lab or to create the  beginnings

 beginnings of of an an m-file.m-file.

End of the Tutorial

End of the Tutorial

At this point, you should know enough to maneuver around in Matlab and find whatever else you need. Help is At this point, you should know enough to maneuver around in Matlab and find whatever else you need. Help is available from the built-in

available from the built-in helphelp command, the on-line help system at command, the on-line help system at www.mathworks.comwww.mathworks.com, or fellow students, or fellow students and faculty.

and faculty.

Quest

Questions? ions? Comments? Suggestions?Comments? Suggestions? Contact

References

Related documents