Read through A Graphing Checklist for Physics Graduate Students before submitting any plots in this module. See the course website for the link.

Similar documents
Introduction. Pre-Lab Questions: Physics 1CL PERIODIC MOTION - PART II Spring 2009

LAB 2 - ONE DIMENSIONAL MOTION

Topic 1: Plotting Data Basic introduction to entering and plotting data, displaying error bars and appropriate labels.

Introduction. Pre-Lab Questions: Physics 1CL PERIODIC MOTION - PART II Fall 2009

2: SIMPLE HARMONIC MOTION

Updated 2013 (Mathematica Version) M1.1. Lab M1: The Simple Pendulum

1 Overview of Simulink. 2 State-space equations

Physics 2310 Lab #3 Driven Harmonic Oscillator

DIFFERENTIAL EQUATIONS

PHYSICS 211 LAB #8: Periodic Motion

Linear Motion with Constant Acceleration

Conformational Analysis of n-butane

Lab #2 - Two Degrees-of-Freedom Oscillator

2: SIMPLE HARMONIC MOTION

Lab 10 - Harmonic Motion and the Pendulum

Chapter 1 Linear Equations. 1.1 Systems of Linear Equations

TIphysics.com. Physics. Pendulum Explorations ID: By Irina Lyublinskaya

5-Sep-15 PHYS101-2 GRAPHING

Department of Chemical Engineering University of California, Santa Barbara Spring Exercise 2. Due: Thursday, 4/19/09

Lab 1: Dynamic Simulation Using Simulink and Matlab

Student Instruction Sheet: Unit 3, Lesson 3. Solving Quadratic Relations

Lab 2 Worksheet. Problems. Problem 1: Geometry and Linear Equations

first name (print) last name (print) brock id (ab17cd) (lab date)

MASSACHUSETTS INSTITUTE OF TECHNOLOGY Physics Department

EXPERIMENT 7: ANGULAR KINEMATICS AND TORQUE (V_3)

Project 2: Using linear systems for numerical solution of boundary value problems

Physics with Matlab and Mathematica Exercise #1 28 Aug 2012

Using Microsoft Excel

The Spring-Mass Oscillator

ES205 Analysis and Design of Engineering Systems: Lab 1: An Introductory Tutorial: Getting Started with SIMULINK

Lab 11. Spring-Mass Oscillations

Chapter 1 Review of Equations and Inequalities

DON T PANIC! If you get stuck, take a deep breath and go on to the next question. Come back to the question you left if you have time at the end.

LAB 3: VELOCITY AND ACCELERATION

Assignment 1 Physics/ECE 176

Unit 7: Oscillations

Lab 12. Spring-Mass Oscillations

Remember that C is a constant and ë and n are variables. This equation now fits the template of a straight line:

Experiment: Oscillations of a Mass on a Spring

Motion II. Goals and Introduction

[Disclaimer: This is not a complete list of everything you need to know, just some of the topics that gave people difficulty.]

Lab 5: Nonlinear Systems

Project 3: Pendulum. Physics 2300 Spring 2018 Lab partner

Damped harmonic motion

Physics 212E Spring 2004 Classical and Modern Physics. Computer Exercise #2

Lab 11 Simple Harmonic Motion A study of the kind of motion that results from the force applied to an object by a spring

LAB 3 - VELOCITY AND ACCELERATION

EEE161 Applied Electromagnetics Laboratory 1

Topic 5 Notes Jeremy Orloff. 5 Homogeneous, linear, constant coefficient differential equations

LAB 1: MATLAB - Introduction to Programming. Objective:

Spring Thing: Newton s Second Law. Evaluation copy

Work and Energy Experiments

Introduction to Computer Tools and Uncertainties

SHM Simple Harmonic Motion revised May 23, 2017

Homework 1 Solutions

MATLAB Ordinary Differential Equation (ODE) solver for a simple example 1. Introduction

Mechanics, Heat, Oscillations and Waves Prof. V. Balakrishnan Department of Physics Indian Institute of Technology, Madras

a. Follow the Start-Up Procedure in the laboratory manual. Note the safety rules.

Good Vibes: Introduction to Oscillations

Deep Algebra Projects: Algebra 1 / Algebra 2 Go with the Flow

Physics 4C Simple Harmonic Motion PhET Lab

Please bring the task to your first physics lesson and hand it to the teacher.

LAB 3: WORK AND ENERGY

Writing Circuit Equations

Born simulation report

Simple Harmonic Motion

Moving into the information age: From records to Google Earth

Introduction to Algebra: The First Week

PHY221 Lab 2 - Experiencing Acceleration: Motion with constant acceleration; Logger Pro fits to displacement-time graphs

Simple Harmonic Motion

Simple Harmonic Motion - MBL

Lecture 5b: Starting Matlab

Vibratory Motion -- Conceptual Solutions

Inverted Pendulum System

1 Newton s 2nd and 3rd Laws

Physics 201 Lab 2 Air Drag Simulation

A First Course on Kinetics and Reaction Engineering Example S5.1

MASSACHUSETTS INSTITUTE OF TECHNOLOGY Physics Department. Experiment 03: Work and Energy

Laboratory handouts, ME 340

Gravity: How fast do objects fall? Teacher Advanced Version (Grade Level: 8 12)

PHY 123 Lab 10-Simple Harmonic Motion

MAT 275 Laboratory 4 MATLAB solvers for First-Order IVP

Created: 2/3/96 Modified: September 29, Author: Theresa Julia Zielinski Page 1

Physics 326 Lab 6 10/18/04 DAMPED SIMPLE HARMONIC MOTION

Chem 3502/4502 Physical Chemistry II (Quantum Mechanics) 3 Credits Spring Semester 2006 Christopher J. Cramer. Lecture 9, February 8, 2006

Lab 1g: Horizontally Forced Pendulum & Chaotic Motion

MAT 275 Laboratory 4 MATLAB solvers for First-Order IVP

Lab Partner(s) TA Initials (on completion) EXPERIMENT 7: ANGULAR KINEMATICS AND TORQUE

ACCESS TO SCIENCE, ENGINEERING AND AGRICULTURE: MATHEMATICS 1 MATH00030 SEMESTER / Lines and Their Equations

2 Background: Fourier Series Analysis and Synthesis

Chapter 4. Oscillatory Motion. 4.1 The Important Stuff Simple Harmonic Motion

Lab 4: Gauss Gun Conservation of Energy

ODEs. September 7, Consider the following system of two coupled first-order ordinary differential equations (ODEs): A =

x = B sin ( t ) HARMONIC MOTIONS SINE WAVES AND SIMPLE HARMONIC MOTION Here s a nice simple fraction: y = sin (x) Differentiate = cos (x)

Finding Limits Graphically and Numerically

Department of Chemical Engineering University of California, Santa Barbara Spring Exercise 3. Due: Thursday, 5/3/12

Introduction to Simple Harmonic Motion

Laboratory handout 5 Mode shapes and resonance

New Mexico Tech Hyd 510

Algebra Exam. Solutions and Grading Guide

Transcription:

Module C2: MatLab The Physics and Astronomy Department has several copies of MATLAB installed on computers that can be accessed by students. MATLAB is a highly developed software package that allows the user to analyze data sets, functions, and differential equations. There are numerous books available, some of which may be found in the library. If you use a book, make sure that it is not more than a few years out of date. In what follows, I will illustrate how MATLAB can be used to solve several problems in physics. Be aware that, as with most well developed programs, there are multiple methods to achieve the same result. You may discover these other methods by perusing books, MATLAB manuals, and MATLAB help. This brief introduction to MATLAB is not intended to be the final word on this topic. Anticipate needing to use the MATLAB help menu and the MATLAB manuals as you work through this. Working through this module is similar to working through other problem sets: you should expect to make a lot of mistakes the first time you try to solve a problem. The advantage of software is that it generally lets you know right away that you have made a mistake. The disadvantage is that it is not always obvious what mistake it thinks you have made. Read through A Graphing Checklist for Physics Graduate Students before submitting any plots in this module. See the course website for the link. Copyright 2016 Marshall Thomsen 1

MODULE C2 Name: Term: Problem Max 1 st 2 nd Final 1 10 2 10 3 10 4 10 5 10 6 10 7 10 TOTAL 70 Copyright 2016 Marshall Thomsen 2

Problem 1: Coupled Oscillators This standard intermediate mechanics problem illustrates how we can make good use of matrix manipulation in MATLAB. I will begin by describing the physics of the situation. Consider three masses attached to each other and to walls by four springs, as shown: Label the springs from left to right k 1, k 2, k 3, and k 4, and the masses, m 1, m 2, and m 3. Note: the following equation should make sense to those of you who have studied Lagrangians. Don t worry about it if you have not (although consider taking module M2). For this system, the Lagrangian can be written as L = 1 2 m 1 x 2 1 + 1 2 m x 2 2 2 + 1 2 m x 2 3 3 1 2 k 1x 2 1 1 2 k 2 x 2 x 1 ( ) 2 1 2 k 3( x 3 x 2 ) 2 1 2 k 2 4x 3 The resulting equations of motion for the position of the three masses are m 1 x 1 + ( k 1 + k 2 )x 1 k 2 x 2 = 0 ( )x 2 k 2 x 1 k 3 x 3 = 0 ( )x 3 k 3 x 2 = 0 m 2 x 2 + k 2 + k 3 m 3 x 3 + k 3 + k 4 We will look for solutions of the form x 1 = a 1 cosωt x 2 = a 2 cosωt x 3 = a 3 cosωt These are known as normal mode solutions each mass will oscillate with the same frequency but may oscillate with different amplitude. When we solve this problem we will find that there are three different normal modes each with its own frequency. Keep in mind, however, that when a system oscillates in a normal mode, all masses oscillate with the same frequency. That is, ω 1 is the frequency of ALL the masses when the system oscillates in the first normal mode; it Copyright 2016 Marshall Thomsen 3

is NOT the frequency of just m 1. We plug this solution into the equations of motion above and find that the cosine terms cancel, leaving m 1 ω 2 a 1 + ( k 1 + k 2 )a 1 k 2 a 2 = 0 m 2 ω 2 a 2 + ( k 2 + k 3 )a 2 k 2 a 1 k 3 a 3 = 0 m 3 ω 2 a 3 + ( k 3 + k 4 )a 3 k 3 a 2 = 0 or, rearranging the terms, ( k 1 + k 2 ) ω 2 m 1 a 1 k 2 a m 2 + 0a 3 = 0 1 ( ) k 2 a m 1 + k + k 2 3 ω 2 2 m 2 a 2 k 3 a m 3 = 0 2 ( ) 0a 1 k 3 a m 2 + k + k 3 4 ω 2 3 m 3 a = 0 3 These equations have a solution provided the determinant of the coefficients is zero: ( k 1 + k 2 ) ω 2 k 2 0 m 1 m 1 k 2 ( k 2 + k 3 ) ω 2 k 3 = 0 m 2 m 2 m 2 0 k k 3 ( 3 + k 4 ) ω 2 m 3 m 3 Mathematically, this problem is identical to finding the eigenvalues, λ=ω 2, of the matrix ( k 1 + k 2 ) k 2 0 m 1 m 1 k k 2 ( 2 + k 3 ) k 3 m 2 m 2 m 2 0 k k 3 ( 3 + k 4 ) m 3 m 3 We will use MATLAB to compute these eigenvalues. To get started, let s first look at a simple, specific case. Set all of the k values equal to 10 N/m and all of the m values equal to 2kg. The matrix becomes (ignoring units) Copyright 2016 Marshall Thomsen 4

10 5 0 5 10 5 0 5 10 Start MATLAB. In the command window, enter the above matrix (giving it the name A) by typing in the following: >>A=[10,-5,0;-5,10,-5;0,-5,10] This is the brute force method for entering in a matrix, element by element. Individual elements are separated by spaces or commas and rows are separated by semicolons. When you hit return after typing this line, you should see the matrix typed out in the 3X3 format as above. The quickest way to get the eigenvalues is to type eig(a) and hit return. You should see displayed: ans = 2.9289 10.0000 17.0711 Right now, these results are stored in the variable ans, which is the default name given to the result of any calculation. Let s store these results in lambda by entering lambda=eig(a). Now you will see lambda = 2.9289 10.0000 17.0711 The frequencies we are after are the square root of these eigenvalues. MATLAB allows you to manipulate all of the elements of a matrix in a single line. To indicate that you want an operation carried out element by element, you just need to type a period after the matrix name and before the operation: omega=lambda.^0.5 Copyright 2016 Marshall Thomsen 5

The result is omega = 1.7114 3.1623 4.1317 which are our frequencies in units of rad/s. Assignment 1: Repeat the above calculations allowing m 2 to vary, using the following values: 0.2kg, 1kg, 2kg (should be identical to what we did), 4kg, 20kg. Submit for each value of m 2 a listing of the matrix A and the resulting values of ω. These are easily copied and pasted into a word processing document. At the end of that document, include a brief discussion of trends you notice. We can take advantage of matrices further and avoid having to run this routine manually multiple times. Enter the desired matrix values using the following format: >>m2=[0.2 1 2 4 20] Next we will step through the calculations one by one using a for/end loop. This loop begins with for i=j:k, where i is a variable whose initial value is j. The statements following the for statement and up to the end statement are executed for that value of i. Then i is incremented by 1 and the process repeats, until i reaches the final value, k. See the MATLAB help utility for variations on for/end loops. Here is what you should type in: >>A=[10-5 0; 0 0 0;0-5 10] >>for i=1:5 A(2,1)=-10/m2(i); A(2,3)=A(2,1); A(2,2)=20/m2(i); lambda=eig(a); mass=m2(i) omega=lambda.^0.5 end Comments: I initialized the values of A which will not change as m 2 changes and entered zero for the middle row. While generally MATLAB immediately tells you the result of a calculation, when you are entering a for/end loop, it will not write anything out until you type end and hit return. Another way to get MATLAB to not immediately write out a result is to end a line with a semicolon. By doing so inside this loop, we avoid having the A matrix written out every time an element is assigned a new value. The last two lines before the end statement are written without a semicolon specifically to allow the results to be written. Copyright 2016 Marshall Thomsen 6

If you need to modify what you ve written (perhaps it has not run right because you made a typing mistake), copy the entire block of statements and paste it into the new command line. You can edit as usual, with the exception that whenever you hit return, MATLAB will immediately begin the calculation. If you want to insert a new line in the middle of your loop, try shift+return (that is what works on a Mac). If you have entered the program correctly, you should reproduce your results from assignment 1. A more compact representation is obtained by modifying the program as follows: >>for i=1:5 A(2,1)=-10/m2(i); A(2,3)=A(2,1); A(2,2)=20/m2(i); lambda=eig(a); omega(i,1:4)=[m2(i);lambda(1:3).^0.5]; end A single omega matrix (5x4) contains the masses in the first column and the values of omega in the next three columns. The assignment statement, omega(i,1:4)=[m2(i);lambda(1:3).^0.5]; enters data into row i, each time through the loop. The second index takes the form 1:4, telling MATLAB to step through the indices from 1 to 4, one at a time. The right hand side contains 4 values in the bracket, the last three of which are determined by a three element matrix whose indices are expressed compactly as 1:3. Since I have included a semicolon after this assignment statement, if we want to see the results after the loop has run, we need to ask MATLAB. This is most simply done by typing omega and hitting return. If we are preparing to graph a relationship, it is often useful to have a set of numbers representing the independent variable (in this case, m2) that increase at regular increments. We can compactly generate these sets using a variation of the colon operation. Enter the following: m2=[1:0.2:2] When you hit return, you should find the values of m2 are now regularly spaced as 1.0, 1.2, 1.4, 1.6, 1.8, 2.0. Copy the loop program and paste it into the new command line. Change the upper limit of i from 5 to 6 and run the program. Omega should now read 1.0000 5.1167 3.1623 1.9544 1.2000 4.8012 3.1623 1.9013 1.4000 4.5675 3.1623 1.8504 1.6000 4.3879 3.1623 1.8017 1.8000 4.2462 3.1623 1.7554 2.0000 1.7114 3.1623 4.1317 Let s plot the first value of ω as a function of m 2. The plot command is simple: plot(x,y) plots the elements in the vector y as a function of the elements in the vector x. If x and y are column Copyright 2016 Marshall Thomsen 7

or row vectors of the same size, the plot command is as simple as given above. Our date is in a two dimensional matrix, so we need to be more careful how we tell MATLAB to seek out the data. Enter: plot(omega(1:6,1),omega(1:6,2)) This tells MATLAB to look at the first 6 elements of column 1 and the first six elements of column two for the x and y values respectively. When you hit return, a new window should open up called Figure 1. The result I found is At first glance, this looks odd. Why should there be a sudden change in the function at m 2 =1.8kg? If we look back at the omega matrix, we find that the eigenvalues are not always produced in the same order. We can correct that by sorting the matrix rows (excluding the first column) in order of increasing size. Enter: for i=1:6 omeganew(i,1)=omega(i,1); omeganew(i,2:4)=sort(omega(i,2:4)); end Copyright 2016 Marshall Thomsen 8

This loop goes through the rows one at a time and sorts entries in columns 2-4 (where ω values are stored) and places them in order of increasing size. When you type omeganew, you should see the new matrix with properly sorted values of the frequency. The values we were plotting are now mostly in column 4. Let s plot that column now: plot(omeganew(1:6,1),omeganew(1:6,4)) Labels may be applied using either Edit/Axes Properties or Insert/X Title. To display all three frequencies on a single plot, enter plot(omeganew(1:6,1),omeganew(1:6,2:4)) The first argument specifies the x values and the second instructs MATLAB to look in columns 2 through 4 for y values. Once titles are added, the result is Copyright 2016 Marshall Thomsen 9

Assignment 2: Using the same mass and spring system as described above, plot the three normal mode frequencies when all of the masses are fixed at 2 kg, k 1 and k 4 are fixed at 10 N/m, and k 2 =k 3, with those values ranging from 1 N/m to 20 N/m. Submit a copy of your plot as well as all MATLAB programming lines used to generate data for the plot and the plot itself. Copyright 2016 Marshall Thomsen 10

Problem 2: Motion in the presence of a complicated force. Sometimes, the potential energy associated with two atoms or molecules weakly attracting each other is modeled with the use of the Lennard-Jones potential: a 12 a6 V (r) = V o 12 r r 6 where a and V o are constants that help set the length and energy scale respectively. Lennard-Jones Potential 2 1.5 1 V/Vo 0.5 0 0 0.5 1 1.5 2 2.5 3-0.5-1 r/a Notice the steep increase in the potential as the two molecules approach each other that is the hard core repulsion associated with the fact that the two molecules cannot occupy the same position. On the other hand, at somewhat larger distances the molecules weakly attract due to electronic interactions. The result is an equilibrium position where the potential is a minimum (at r approximately equal to 1.12a). For simplicity, let s consider a single particle of mass m moving in the presence of a one dimensional Lennard-Jones potential: F x = dv dx = d dx V a 12 a6 12a 12 o 12 x x 6 = V o + 6a6 12a 12 x 13 x 7 = V o 6a6 x 13 x 7 F x = ma x 12a 12 V o x 13 6a6 x 7 = m d 2 x dt 2 Copyright 2016 Marshall Thomsen 11

In preparation for numerical analysis, I will convert the variables to dimensionless form. Since a has length units, the obvious dimensionless position variable is Y=x/a. It turns out that ma 2 V o has units of time, so τ = t motion becomes d 2 Y dτ = 12 2 Y 6 13 Y 7 V o 2 is dimensionless. After substitution, the eqution of ma MATLAB has a convenient tool for solving systems of first order differential equations. We can convert this single second order differential equation into two coupled first order differential equations by introducing the velocity variable, v Y : v Y = dy dτ dv Y dτ = 12 Y 6 13 Y 7 To program this, first it is useful to introduce m-files. These files always end with the extension m. That is, one might be called filename.m. Functions that you create and plan to use repeatedly can be stored in an m-file. Let s program the second of the above two equations as an m-file. First, pull down the File menu, select New File and then m-file. This should open up a new window. Enter the following: function acc=vyprime(y) %This is the acceleration function corresponding to a Lennard-Jones %potential. acc=12*y.^(-13)-6*y.^(-7); end Next save the file as vyprime.m. It is probably safest to use whatever directory that shows up as a default. If you are doing this on a computer that someone else has done this exercise on, add your initials to both the file name and the function line [acc=qqqvyprime (y); save as QQQvyprime.m] so that you do not overwrite someone else s file. Every subsequent reference to vyprime should use the name you have given it. Functions are often used to store lines of code for repeated use. For this reason, it is very helpful to add some documentation to the function. Comment lines in MatLab are preceded by the % sign. Now, leaving the m-file window open (you may need to edit this later) switch back to the command window. First we will plot this function to see what it looks like. At the command line >> enter Y=[0.5:0.05:2]; and then plot(y,vyprime(y)). Note that the variable name Y does not have to be the same as the variable name in the M-file. I could just as well have entered >>Q=[0.5:0.05:2]; >> plot(q,vyprime(q)) The plot window should show a function that rapidly drops to values very close to zero. Copyright 2016 Marshall Thomsen 12

Comment on the punctuation: The semicolon in the function and on the command line once again ensures that MATLAB does not write a result onto the screen for every calculation. Assignment 3: Suppose a particle of mass m experiences a potential energy of the form V x ( ) ( ) = V o e 2 x b e x b where V o and b are constants. a. Choose suitable dimensionless variables and transform this equation into one involving those variables. b. Calculate the force function associated with this dimensionless potential. c. Create two m-files, one for the dimensionless potential energy function and one for its derivative, then plot these functions over an interval which demonstrates the key features of the function. Among other things, you want to make sure you can clearly see the minimum in the potential energy function. You should submit your calculations for parts (a) and (b), a copy of your m-files, and your plots for part (c). Make sure to include comment lines in your m-files. Now we need an m-file suitable for use in the differential equation solver. We recognize that Y is a function of time, τ. Even though τ does not appear explicitly in the definition of our function, it is a variable relevant to the differential equation and hence needs to be specified in the function. Furthermore, we need to define two functions to account for the two differential equations. MATLAB wants these equations to be entries in a single matrix. Let s define z(1)=y and z(2)=dy/dτ=v Y. Our equations to solve then have the form dz( dτ = z( 2) dz( 2) dτ 12 = [ z( 1) ] 6 13 z 1 [ ( )] 7 We will define a new function, lennard(t,z), which represents both of these derivatives. Open a new m-file and enter function dzdt=lennard (t,z) %These are the coupled differential equations that describe motion of an %object in a Lennard-Jones potential. z(1) stores the position information %and z(2) stores the velocity information. dzdt(1,1)=z(2); dzdt(2,1)=12*z(1)^(-13)-6*z(1)^(-7); end Save this as lennard.m. The differential equation solver expects the equations to be located in column vectors. If I had used just a single argument for dzdt, MATLAB would have treated the array as a row vector. (There are other ways for handling this issue.) Copyright 2016 Marshall Thomsen 13

Now back in the command window, it is simple to ask MATLAB to solve this system of equations. If you read a manual, you will find there are several differential equation solvers. Try ode45 first if that does not work on your problem, read a manual to get other suggestions. Enter the following command: >>[t,z]=ode45(@lennard,[0,20],[1.05; 0]) This asked MATLAB to solve the coupled first order differential equations defined by the function lennard. The variable t ranges from 0 to 20. The initial value of z(1) is 1.05 and the initial value of z(2) is 0. Physically this means the particle started at Y=1.05 with a velocity of zero. When this command is executed, data for t and z will be displayed on the screen. Plotting the results is a one line operation: >>plot (t,z) Notice the position oscillates between 1.05 and about 1.25, for an amplitude of about 0.10. The velocity oscillates about zero, as it must for periodic motion. The velocity oscillations are clearly not sinusoidal, due to the asymmetric nature of the potential function. There look to be 11 minima in the position function during the 20 seconds plotted. This corresponds to 10 complete cycles and therefore the period of the motion is about 2 in dimensionless units. For very small oscillations, this potential can be treated like a harmonic oscillator. It can be shown that in dimensionless units, the period would be Copyright 2016 Marshall Thomsen 14

T = 2π 2 1 1 3 2 =1.66 18 Try starting the oscillator at 1.10 instead of 1.05. this starting point is substantially closer to the equilibrium position of 2 1/6 =1.122 and hence will produce smaller amplitude oscillations. What is the period of oscillation now? For contrast, start the oscillator at 1.01 and you should see a much longer period. These plots illustrate a key difference between harmonic and anharmonic oscillators. In anharmonic oscillators, the period of oscillation depends on the amplitude of motion. Assignment 4: Using the same potential function as you used in Assignment 3, write out a differential equation of motion for a particle of mass m in the presence of this potential. Convert the equation to dimensionless form, and then use MATLAB to solve the equation. Take the starting position to be 0.5 in dimensionless units. By studying the data, determine the maximum value of the displacement and the minimum value. Calculate the amplitude by taking the difference between those two values and dividing by two. Finally, create a plot and determine the period of oscillation using the plot. Turn in your plot and your values for the period and amplitude. The differential equation solver produces an array of data. To determine the maximum or minimum value, one could scan the data or one could let MATLAB do that. For instance, typing at the command line >>max(z) in our Lennard-Jones example worked above produces the result ans = 1.2584 0.3510 Recalling that the first column of the z matrix contains the dimensionless displacement variable and the second contains the dimensionless velocity, we now know the maximum displacement is 1.2584 and the maximum velocity is 0.3510. Similarly, >>min(z) tells us that the minimum displacement is 1.0495 and the minimum velocity is 0.3507. Note that conservation of energy would suggest that the minimum displacement should be 1.05 (the release point), so there is a little error introduced with this numerical solution. The amplitude of the oscillation is (1.2584-1.0495)/2=0.1045. Next let s find where the turn around points are. There are numerous ways to do this, undoubtedly some more efficient than what follows. Nevertheless, here is one approach. Let s focus on when the velocity changes sign. It does so twice in every cycle. We will define a new matrix as the product of successive velocity values. This product will be negative only when the velocity changes sign. Actually, since we are interested in the sign only, let s focus on that. Entering x=sign(y) causes MATLAB to assign +1 to x if y is positive and 1 to x if y is negative. Enter the following at the command line >> for jz=1:380 Copyright 2016 Marshall Thomsen 15

zswitch(jz)=sign(z(jz,2))*sign(z(jz+1,2)); end Why did I choose 380 as the upper limit for the index? I checked the workspace window and found that z was a 380X2 array. MATLAB chose that size as being appropriate for the differential equations it was asked to solve. You may want to check this value to see if it is appropriate in your case. The second index in the z array, above, is set equal to 2 because that is the column containing the velocity data. When you ask MATLAB to type zswitch (remember to just type zswitch at the command line), you will see an array containing almost all 1 s. The scattered 1 s identify the points when the velocity changes sign. We want to find out what times those switches occur. We could count through the array to determine the position or we could get MATLAB to do the search for us: >> k=find(zswitch==-1) This produces an array, k, containing the indices of all entries in that array whose value is 1. The == is used for a logical statement. That is, we are not asking MATLAB to set zswitch equal to 1, we are asking MATLAB if zswitch is already equal to 1. To find the times, remember that they are stored in the t array (that variable was identified in the call to the differential equation solver). Enter >>t(k) and you should see a column of times, indicating when the object reversed directions. The difference between any adjacent pair of these times is one half the period. We can calculate all of the periods at once using >>for kt=1:19 zperiod(kt)=(t(k(kt+1))-t(k(kt)))*2; end I chose 19 as the index limit because my workspace told me there were 20 entries in the k array (so there were 19 intervals identified). Want to know the average period? Enter >> period=mean(zperiod) and all of the entries in the zperiod array are averaged. If we wanted to change a parameter in our original function, it would be nice not to need to redo all of these commands. Some commands are conveniently linked together in an m-file. Copyright 2016 Marshall Thomsen 16

function per=aveperiod(z,t) %This function calculates the average period of an oscillator. The %two-column array, z, contains the postion and velocity as a function of %time, with the time elements entered in the array, t. %First, we identify points where the velocity changes sign: zswitch will be %-1 in those cases. dimens=size(z); points=dimens(1); for j=1:(points-1) zswitch(j)=sign(z(j,2))*sign(z(j+1,2)); end %Next, we identify the indices in the z array where these sign switches %occur. k=find(zswitch==-1); changes=size(k); %Finally, we use the indices we have identified to determine the times at %which the velocity changed sign. The elapsed time between two sign changes %is half a period. for kt=1:(changes(2)-1); period(kt)=(t(k(kt+1))-t(k(kt)))*2; end per=mean(period); end The only twist added here is the size command, which determines how many entries there are in the arrays. That is, if z is a 381x2 array, size(z)=[381 2]. By the way, when I wrote this function, I wanted to have a complete list of the periods for each cycle during the entire set of oscillations. This could be particularly useful when there is damping present in that case it turns out that the periods may not always be the same. In this case, though, since there is no damping it is easy to show the period will remain constant once you set the oscillator in motion. A quicker way to set up the calculation, then, would be to just count the total number of cycles and divide that into the elapsed time from the start of the first cycle to the end of the last cycle. Now back at the command line, I can set up a loop to scan through various starting values for the oscillator: >> for ib=1:10 begin(ib)=1.13+ib*0.02; [t,z]=ode45(@lennard,[0,20],[begin(ib),0]); ljperiod(ib)=aveperiod(z,t); end The initial positions are stored in begin and the resulting periods in ljperiod. Here is the plot: Copyright 2016 Marshall Thomsen 17

Assignment 5: Using the same potential as you used in Assignment 4 and using the same method for defining the amplitude, explore the variation of the period with respect to the amplitude, using m-files to code the differential equations (analogous to the one I called lennard), to calculate the period (if you coded the aveperiod one for practice, that should work), and to calculate the amplitude. The amplitude m-file can be built with the use of the max and min functions (see MATLAB help). The plot of the period versus the amplitude should be smooth and monotonic. I found it necessary to adjust the length of time looked at by ODE45 (i.e., increase the time interval from [0,20]) in order to smooth the plot out. Submit printouts of your properly documented m-files and a copy of a properly labeled plot of period versus amplitude. Copyright 2016 Marshall Thomsen 18

Problem 3: Electric potentials: an example of 3D plotting The electric field due to an infinitely long, straight line of charge (λ=charge per unit length) has magnitude λ E = 2πε o r where r is the distance from the point at which the field is measured to the line of charge. The potential difference between two points in the vicinity of this distribution is V 2 V 1 = λ ln r 1 2πε o r 2 Consider two lines of charge parallel to the z axis. The first has charge λ o and passes through the point x=d y=0, and the second has charge λ o and passes through the point x=-d, y=0. Let us assume that the point x=0, y=0, z=0 is the reference point at which V=0. Our goal is to calculate the electric potential as a function of position in the xy plane. We will need to calculate two values of the potential difference, one for each line of charge, and add them. For both calculations, the reference point is the origin, so r 1 will represent the distance between the origin and the line of charge (D in both cases) and r 2 will represent the distance between the point at which the potential is being calculated and the line of charge. Thus, V ( x, y) = λ o ln 2πε o V ( x, y) = λ o ln 2πε o V ( x, y) = λ o D 2πε o ln + λ o ( x D) 2 + y 2 ( x + D) 2 + y 2 ( x D) 2 + y 2 ln ( x + D)2 + y 2 4πε o x D ( ) 2 + y 2 D ( x + D) 2 + y 2 We can define dimensionless variables, V 1 =V/(λ o /4πε o ), x 1 =x/d and y 1 =y/d: ( ( ) = ln x +1 1 ) 2 2 + y 1 ( x 1 1) 2 2 + y 1 V 1 x 1, y 1 To create a three dimensional plot, the first step is to establish a set of points over which the function will be evaluated. In this case, we want to be sure to avoid the points (x,y)=(1,0) or (- 1,0) since that will cause problems with the natural log function. We can define the set with the following command: >> [x,y]=meshgrid(-3.05:0.1:3.05,-3.05:0.1:3.05); Notice that by choosing 3.05 as a starting value and incrementing by 0.1, we ensure that +1, 0, and 1 are all missed. The next step is to evaluate our function at every point on the grid: Copyright 2016 Marshall Thomsen 19

>> v=log(((x+1).^2.+y.^2)./((x-1).^2.+y.^2)); MATLAB uses log to represent the natural log. The periods prior to the squaring and dividing operators ensure that the calculation is carried out element by element on the x and y matrices. x^2 means square the matrix x, while x.^2 means square each element in the matrix (which is what we want to do here). Lastly, we can create a surface plot using >> surf(x,y,v) The result should look like Copyright 2016 Marshall Thomsen 20

Under the View menu, you can open up all of the toolbars and spend some time exploring. The perspective and apparent lighting can be changed, among other things. Copyright 2016 Marshall Thomsen 21

Assignment 6: The Van der Waals model for a gas can be expressed in dimensionless variables as P r + 3 2 v r v 1 r 3 = 8 3 T r where P r = P v v P r = T critical v r = critical T T critical The critical pressure, volume and temperature are experimentally measurable quantities. When the temperature is less than the critical temperature (i.e., T r <1) there exists a phase transition from the liquid to the vapor phase (at the appropriate pressure). Above the critical temperature, no such phase transition exists. Create a three-dimensional plot (axes labeled) depicting the relationship between P r, v r, and T r. Keep in mind that pressure and temperature should be positive variables and hence v r cannot fall below 1/3. You should submit at least two perspectives (two rotations) of your plot and a brief discussion about the qualitative differences in the plot for T r >1 and T r <1. When you choose the increment in your meshgrid statement, keep in mind that number determines the spacing of the lines on your contour plot. If you make the increment too small, the lines are packed together so closely that the entire plot looks black. If you make the increment too big, then the plot becomes angular (that is, it is not smoothed out enough). You will also discover that even if you take your volume variable to be greater than 1/3, there are certain combinations of temperature and volume that will give rise to negative (and hence unphysical) values of pressure. It took me a little bit of time to figure out how to select appropriate ranges for volume and temperature so thatthere were no negative values of pressure AND I could see enough detail in the plot to that the different in behavior for T r >1 compared to T r <1 was clear. Copyright 2016 Marshall Thomsen 22

Now for one more problem that combines several skills you have acquired: Assignment 7: An object of mass 0.55kg is launched vertically upward with an initial speed v o. It experiences both linear and quadratic air resistance, so that its motion is determined by the equation m d 2 y dt = mg c 2 1 where dy dt c 2 dy dt dy dt c 1 = 0.25 kg c s 2 = 0.015 kg m Use MATLAB s differential equation solving tools to solve this equation for v o equal to 5 m/s, 10 m/s, and 20 m/s. Plot the height as a function of time, showing all three curves (corresponding to the three initial conditions) on a single graph. Assume the object is launched from ground level and hence the minimum value of y is zero. If the differential equation solver returns negative values of y, they should be set equal to zero. In this problem, you will probably find it easier to code the equation as given rather than convert it into dimensionless variables. Your final plot should include both axis labels and a properly labeled legend. (Hint after inserting the legend, click, or double click, on the text to edit it). Submit a copy of your programming code (including any M-files you created) and a printout of your plot. One issue that trips up many students on this problem: each time ODE45 is called, the default is for MatLab to choose a grid of time values that most efficiently solves the differential equation over the specified time period. This grid of points varies from one application to the next. So each time you call ODE45, you will have a new array of time values to keep track of. Copyright 2016 Marshall Thomsen 23