Document 10543300

advertisement
MATLAB Introduction for Physics of the Earth Students By: Jonathan R. Delph & Jared Olyphant with helpful input from Randy M. Richardson University of Arizona Geophysical Society (UAGS) www.facebook.com/UAGeophysicalSociety Sept. 2 & 4, 2014 Introduction to MATLAB Download material from www.geo.arizona.edu/cdcat/JonathanDelph/UAGS Part A: User Interface When you first open MATLAB, the default gui (graphical user interface) window displays a variety of information that will be helpful when using the product. Below is an example of what you might see: Current Folder: Pretty self-­‐explanatory; this window tells you what is in the folder that you are currently running MATLAB in. If you attempt to run a script or read in a data file, it needs to be located in your current folder. Details: This small region will give you detail about a MATLAB script based on the first lines of the script. We will get more into this later. Command Window: This is where you can enter MATLAB based commands. In this introduction, we will use this mostly for entering mathematical operations. Workspace: The Workspace is very important, as it tells you what variable MATLAB currently has in memory. These variables should be cleared before running a new set of MATLAB commands in order to avoid overwriting variables and ending up with a wrong solution for your problem. These can be clear using the “clear all” command in the Command Window, or individual variables can be cleared using “clear variablename”. Command History: MATLAB keeps a record of the recent commands that you have entered into the Command Window. This can be useful if you are troubleshooting a script, and the command is very long. These can also be scrolled through by pressing the “up” arrow on your keyboard in the Command Window. MATLAB Documentation and the “Help” command You will find that, while MATLAB has a steep learning curve, it is extremely well documented. The circled question mark icon (see icon below) at the top of the MATLAB interface is very useful when searching for commands or looking for help with syntax (syntax is the format in which you must enter a command in order for MATLAB to understand it). If you know a command, and only need help with the syntax, you can also type “help command” in the Command Window. Google can also be a very useful friend in your time of need. Part 1. Basic algebra Addition, subtraction, multiplication, and division are all straight-­‐forward MATLAB procedures; 1 + 4 = 5 2 – 4 = -­‐2 5 * 5 = 25 25/5 = 5 In matlab, we can define the outputs to be variables for use in later calculations: a = 5 + 4 Output: “a = 9” Square-­‐roots are commonly taken to get the absolute value of a function or the magnitude of a vector. A straight forward way to do this is: a^(1/2) = 3 where “^” means “raised to the power.” However, MATLAB has functions for many common mathematical functions like the one above: sqrt(a) = 3 There are many other common functions in MATLAB (such as mean, mode, and standard deviation functions) that can save you a lot of scripting time if you know they exist. If it is a common mathematical operation, you can try searching the “Product Documentation” (question mark at the top of the command window). Part 2.1 Matrix Manipulation: Italics indicate text to type into command window Typical operators, such as “ + -­‐ * /” work well for scalar values, but MATLAB was designed specifically to work with matrices (else, it is just a expensive, advanced calculator). This means that we must understand matrix algebra operations to obtain the answer we would like. Let’s begin by creating a vector: A = [ 1 4 3 5 ] % This creates a vector A and by default prints it A = [ 1 4 3 5 ] ; %The semicolon suppresses the output of A to the command window MATLAB default for matrices creates a row vector. However, in matrix algebra, column vectors are usually preferred. Creating a row vector tends to be much faster than creating a column vector in MATLAB, as you are required to place a “;” between each row in a vector. E.g.: A = [ 1 4 3 5 ] is a 1x4 row vector, while A = [ 1; 4; 3; 5 ] is a column vector. The difference between these matrices is easily seen by typing the MATLAB function size(A) into the command window. To transpose a matrix (i.e. make a row vector a column vector, more commonly used in matrix operations, or in general to interchange rows and columns in a matrix), an apostrophe can be added to the variable: B = A’ or B = [ 1 4 3 5 ]’ B is now the transpose of A. In general, many errors that beginners come across involve when to use whole matrix operations versus piece-­‐wise (or element-­‐wise) operations. The Matlab matrix multiplication B * C creates the product of B “times” C, achieved by multiplying the rows of B times the columns of C, and will result in an error unless the number of rows in B equals the number of columns in C. Thus, for example, typing the following will result in an error: A * A because A is a 1 x 4 “matrix”, and by definition, a 1 x 4 matrix cannot be multiplied by a 1 x 4 matrix. Sometimes, however, what is really wanted is element-­‐by-­‐element multiplication of two arrays of the same dimension (often the same array, in fact), called array multiplication. Thus A .* A results in [1 16 9 25], an array of the same dimension as A where each term has been squared. This “dot” nomenclature applies to all matrix algebra operations (e.g. multiplication, division, squaring), and remembering this will save a lot of time fixing errors. In general, you can always incorporate the “dot” to the algebra operation, as this will not change the result of scalar algebra (e.g. a * a = a .* a, if a is a scalar). Part 2.2 Referring to a matrix location Let’s make a 3x2 matrix (remember, first number is # of row, second is # of columns): B = [ 5 3 ; 3 2; 0 9 ] 5 3 3 2 0 9 If we would like to refer to a specific number in this matrix, we can refer to it by its position in the matrix: B(2,2) will get the number in the second row and second column of the matrix. “ = 2” This is particularly useful later when we are using loops to populate a matrix. Lastly, remember that all matrices must follow basic matrix algebra rules, meaning that the # of colums in the first matrix must equal the number of rows in the second matrix when performing operations like multiplication and division. And the size of the matrix must be equal for addition or array multiplication. Part 3. Editor Window The editor window is used to create scripts. Scripts are useful when writing a difficult math problem with multiple variables or iterative calculations, and can help you keep things in order. There are a couple outstanding reasons why writing scripts is more useful than using the command window: 1) It is easier to troubleshoot scripts should you have an error with your commands 2) If you envision yourself doing a similar problem in the future, you can go back to these scripts, change the variables, and re-­‐run the script to get a new answer. 3) If there is an error in your “loop”, you will not have to re-­‐type the entire loop; you can simply fix the error and re-­‐run your script. To open the Editor Window, click on the “New Script” button in the top-­‐left corner of the MATLAB Graphical User Interface (see orange box on image below). Clicking this icon will open up a black MATLAB “script”. 3.1 Loops: Loops are particularly useful for tedious operations where the same equation is used multiple times with different values to obtain an answer. Depending on the type of loop, we can tests cases (if, while) or do an operation iteratively (for). “For” loops: For loops tend to be the most commonly used in MATLAB (in my experience). The basic logic of the for loop is “This operation will occur a number “n” times”. Let’s try a simple one: A = [ 4 2 4 9 ]
% create a 1x4 row vector
length(A) %length is a command that tells you how “long” the vector is.
for n = 1:length(A)
% Initiate for loop from 1 to length(A)
disp(n)
% Display the counter “n”
end
% Terminate the “for” loop
The “:” indicates that we are going from 1 “to” the length of A (implicitly in steps of 1), which is 4. If we type this in independently in the terminal, we will get the output: n = 1 2 3 4 To run this script, hit the green arrow labeled RUN at the top of the editor window. We can use this to refer to the specific locations in “A” as well. Change the “for” loop to the following: for n = 1:length(A)
% Initiate for loop
%Display the following phrase with values for A(n) and n
sprintf('A(n) = %2.0f and n = %2.0f', A(n),n)
end
% Terminate the for loop
We have added some syntax that we have not used before in this for loop: -­‐ sprintf is a command that writes out values to the command window during calculations -­‐ The “%2.0f” tells sprintf what kind of formatting to use for the displaying of the variables. These should be placed wherever you want a variables real value to show up. % tells sprintf that it is a variable 2 tells sprintf how many spaces to print before the output .0 tells how many decimal places to print f is the format of the number (i.e. f = fixed point, e = scientific notation) for more on “sprintf” and formatting, go to the MATLAB help and type “sprintf” or type “help sprintf” in the command window. “If” Loops: If loops are commonly used inside of “for” loops and tell the script to do certain commands “if” a defined variable is a certain value. Let’s add an “if” statement to our script: A = [ 4 2 4 9 ]
% create a 1x4 row vector
length(A) % length is a command that tells you how long the vector is.
for n = 1:length(A)
% Initiate for loop
if n == 3
sprintf('A(n) = %2.0f and n = %2.0f', A(n),n) % Display the counter “n”
end
end
% Terminate the for loop
For this case, the terminal will only show the string defined by sprintf when n = 3. MATLAB understands the two equals signs to mean “if n equals”, whereas MATLAB interprets only one equal sign to mean “set n equal to 3”. If only one equal sign is used in an if statement, you will receive an error. To make this more complex, we can tell MATLAB to only print the phrase within the “if” statement if the value in A is equal to a number: for n = 1:length(A)
% Initiate for loop
if A(n) == 4
sprintf('A(n) = %2.0f and n = %2.0f', A(n),n) % Display the
counter “n”
end
end
% Terminate the for loop
This “if” statement checks the values in the vector A, and returns a result if it is equal to a user-­‐defined value) Adding “elseif, else” We can use the “if” statement to test multiple cases by adding an elseif or else command. This will allow you to do operations if the variables in the vector your are testing equal a different value (elseif), or don’t equal anything that you have defined (else) for n = 1:length(A)
if A(n) == 4
sprintf('A(%2.0f) is 4!',n)
elseif A(n) > 4
sprintf('A(%2.0f) is greater than 4!',n)
else
sprintf('A(%2.0f) is less than 4!',n)
end
end
Using AND or OR in an If statement AND (&&) or OR (||) test can be used in an “if” statement to tell an operation to only occur when both cases or satisfied (&&) or if only one of the two cases is satisfied (||): AND case: for n = 1:length(A)
if A(n) > 3 && A(n) < 5
sprintf('A(%2.0f) is between 3 and 5!',n)
end
end
OR case: for n = 1:length(A)
if A(n) == 2 || A(n) == 9
sprintf('A(%2.0f) is either 2 or 9!',n)
end
end
MATLAB understands all Boolean operators. Here are common Boolean operators that will come in handy when using “if” statements. == If equals =! If does not equal > If greater than < If less than >= If greater than or equal to <= If less than or equal to || or && and “While” loops While loops are used to limit the number of times an operation will occur. The difference between “while” and “for” loops is that “for” loops will do an operation a set number of times, but “while” loops will stop the operation if a value reaches a user-­‐defined threshold. For example: a = 5;
%predefined variable value
n = 0;
%counter value
while a < 20
a = a + 0.85;
n = n + 1;
if a >= 20
sprintf('It took %2.0f iterations for a >= 20',n)
end
end
Here, we do the calculation a + 0.85 until a is greater than or equal to 20, and then stop. Adding an “if” statement tells MATLAB to display the counter (n) when a > 20 so we know how many times the operation ran. More can be learned about if, for, elseif, etc., by typing help if (etc.) from the command window. Practice Problem from Earthquake Seismology!! Wadati Diagrams are commonly used to find the average ratio of P-­‐wave velocity to S-­‐wave velocity below a station. Vp/Vs ratios correlate to chemical compositions, with lower ratios for more felsic rock types (~1.7ish for granite) and higher ratios for mafic rock types (~1.8 for basalt). In the following example, we will find the Vp/Vs ratio of the crust using P and S-­‐
wave travel times. Step 1: Load in the data from the textfile Tp_TsTp.txt. In the first column of this textfile, there are P-­‐wave travel times (in seconds, x-­‐axis) and the second column has the S-­‐
wave minus P-­‐wave travel times (y-­‐axis). To load a textfile, use the MATLAB command load: file=load('Tp_TsTp.txt'); % variable ‘file’ hold seismic data
Now, you have a variable file that is a 13x2 matrix. We can define the P-­‐wave travel times as: Tp = file(:,1);
The colon means that we want ALL ROWS in the first column (i.e. :,1). We can do the same for the second column. These two data are expected to have a linear relationship if the crust has no significant changes in Vp/Vs ratio with depth, defined by: y = [(Vp/Vs)-­‐1] *x + b (no need to write in MATLAB) Let’s plot our data using the MATLAB plot function: plot(x_variable,y_variable,'.')
The ‘.’ tells the plot function to plot these data as points on the grid (default is lines). We can make this plot pretty by adding x and y labels, a title, a legend, and constraining the axes of the plot: xb = min(Tp);
% Find lowest x-axis value
xe = max(Tp);
% Find highest x-axis value
yb = min(Tsp); % Find lowest y-axis value
ye = max(Tsp); % Find highest y-axis value
xlim([xb-0.5 xe+0.5])
% Set x-axis limits
ylim([yb-0.5 ye+0.5])
% Set y-axis limits
xlabel('P-wave Travel Time (s)')
% Label
ylabel('S-wave TT - P-wave TT (s)') % Label
on figure
on figure
x-axis
y-axis
title('Wadati Diagram')
% Give title to figure
legend('Earthquake','Location','Southeast') % Create legend of data
You can learn more about plotting in general by typing help plot, or about specific commands, for example about x limits by typing help xlim. In our particular example your plot should look like the one below: Now, let’s fit a best-­‐fit line to it. We can use the function polyfit. Go to the help and type polyfit to see the syntax for the function. We want a linear fit. Now that we have the slope and y-­‐intercept of the best-­‐fit line, we can plot the line through the data. To do this, we need to create a vector of x values that spans the data space, then we must use the equation of a line to calculate the associated y-­‐
values (y = mx +b): x = [0:1:10];% Create x-axis values for line from 0 to 10 by steps of 1
y = m*x + b; % Calculate y-axis values for line
Now, we can plot this line on the figure with our data. The hold on command will plot on top of the previous figure. % Plot on Figure with earthquakes
hold on
% Tell MATLAB to plot on previous figure without over-writing
plot(x,y,'r')
The ‘r’ flag tells MATLAB to plot this as a red line. We can also do some regression analysis to calculate how well the line fits our data. The linear regression equation is: (𝑦 − 𝑦! )!
!
𝑅 = 1 − (𝑦! − 𝑦! )!
Calculate this in MATLAB using the sum function. The y variable is theoretical values of y that will fall on your best fit line The 𝑦! variable is the y-­‐coordinate of the data we have The 𝑦! is the mean of the y-­‐coordinates of your data. We should add the Vp/Vs ratio and the Regression fit to our plot. Remember, the slope of the line is [(Vp/Vs) – 1], so we should add one to our slope to get Vp/Vs. We can use the text and sprintf functions to place this on our plot: string=sprintf('VpVs ratio = %2.3f',VpVs);
% Write solution for VpVs ratio on figure
text(x_location,y_location,string);
Your final figure should look like the following! 
Download