Notes for Supplementary Course in Physics, 2010 - dirac

**Notes** **for** **Supplementary** **Course** **in** **Physics**, **2010**Thomas Schrøder, updated by N. BaileySeptember 1, **2010**

Contents1 Introduction to MatLab 51.1 What is MatLab? . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2 Gett**in**g started . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.3 Scripts **in** MatLab . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Equations of motion with variable **for**ce 93 Numerical solution of equations of motion 173.1 Euler’s method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.2 The Leap-Frog method . . . . . . . . . . . . . . . . . . . . . . . . 204 Matlab commands 234.1 Simple mathematical functions . . . . . . . . . . . . . . . . . . . 234.2 Other mathematical functions . . . . . . . . . . . . . . . . . . . . 244.3 Mathematical operators . . . . . . . . . . . . . . . . . . . . . . . 244.4 Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.5 Program structure . . . . . . . . . . . . . . . . . . . . . . . . . . 254.6 Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263

4 CONTENTS

Chapter 1Introduction to MatLab1.1 What is MatLab?MatLab is an **in**teractive program **for** numerical computation and data visualization.There are many different toolboxes available which extend the basicfunctions of MatLab **in**to different application areas. This is a short guide to thebasic features of MatLab and designed to give you an **in**troduction to MatLab.The text is **in**tended **for** you to sit down **in** pairs **in** front of the computer, andgo through the exercises **in** the text.1.2 Gett**in**g startedBe**for**e you get started it is important that you have an understand**in**g of howfiles are organized on the computer’s hard disk. It is a good idea to save yourwork on the H: drive (network drive) that can be accessed from any of thecomputers. That way you can reuse the work you have done on one computer ifyou log-on to another computer next time. The files on any drive are organized**in** a tree structure, and you have access to your personal part of the H: drive.Here you can save files, but it is also possible to make directories, **for** example adirectory called ‘SuppPhys’, where you could save all files related to this course.MatLab is a w**in**dows-based program. There are 3 different k**in**ds of w**in**dows:the command w**in**dow, where you control the calculations, graph w**in**dows (figures)and editor w**in**dows, where you can write, save and load programs **for**MatLab (m-files).To get started just double-click on the MatLab icon on your screen and thecommand w**in**dow will appear.• Start MatLab.When MatLab is started the command w**in**dow will appear and you cantype commands after the >>5

6 CHAPTER 1. INTRODUCTION TO MATLAB• Type pwd (Pr**in**t Work**in**g Directory) and MatLab will return the current(work**in**g) directory. If this is not H:, you should change directory to H:by typ**in**g cd H: (cd stands **for** ‘change directory’). Try the command pwdaga**in**.• Now, if you want to make a subdirectory type: mkdir name (mkdir stands**for** ‘make directory’). You change the work**in**g directory to this subdirectoryby typ**in**g cd name.Important: Every time you start MatLab you should make sure you arework**in**g **in** the right directory!• Type x=0:1:10; on the command-l**in**e and press ‘enter’.• Type x and press ‘enter’.MatLab shows you that you have created a vector with 11 elements, i.e. thenumbers 0, 1, .., 10.• Repeat the two po**in**ts above, but use x=0:.5:10;. What is the difference?• Type x(2) and press ‘enter’. What happens?• Type y=2*x and press ‘enter’. What happens? Describe what y is.• Type y=3*x; and press ‘enter’. What happens? What is the effect of thecharacter ‘;’?• Type plot(x,y) and press ‘enter’. What happens?• Type plot(x,y,’*’) and press ‘enter’. What happens?• Type plot(x,y,’.-’) and press ‘enter’. What happens?• Type grid and press ‘enter’. What does this command do?If you know the name of a MatLab-command, but don’t know or don’tremember how to use it, you can type help and then the name of the command.This will give you **in****for**mation on how to use the commandYou can zoom **in** and out on a graph **in** MatLab; you just have to click theappropriate button on the graphical w**in**dow, and then zoom us**in**g the mouse.Try it!You have now experienced a important strength of MatLab: It can do computationswith vectors, which means you with a s**in**gle command can do mathematicaloperations on hundreds or thousands of numbers at once (all the elements**in** the vector). You can get a s**in**gle number out of a vector, if you typex(10) where x is the name of the vector and 10 is the ‘**in**dex’ stat**in**g whatelement **in** the vector you are **in**terested **in**.• What is the **in**dex of the first number **in** a vector?

1.2. GETTING STARTED 7• Plot a graph of the l**in**e given by y = 2x + 4.• Plot a graph of the l**in**e given by 3x + y − 9 = 0.• Type y=x^2 and press ‘enter’. What happens?• Type y=x.^2 and press ‘enter’. What happens now?When you type x^2 or x*x MatLab **in**terprets x as a ‘matrix’ (i.e. twodimensionaltable with numbers) and * is **in**terpreted as a so-called matrixmultiplication.We don’t use these k**in**d of calculations **in** this course.If you **in**stead type y=x.^2, it means that you make a new variable (vectoror matrix) of the same size as x and the elements **in** y becomes the square ofthe correspond**in**g elements **in** x. This is called element-wise multiplication. Ina similar way you can do element-wise division. Try it!• Make a plot of the equation y = 2x 2 − 5x + 2 **in** an appropriate **in**terval.• Do an graphical estimate of the roots of the equation above (i.e. f**in**dthe x-values **for** which y = 0). Compare your solutions to the analyticalsolution. H**in**t: y can be writteny = (2x − 1)(x − 2).• Make a vector t with values from 0 to 2∗π med with a step π/10 (MatLabhas π as a built **in** constant, you can just type: pi).• Create two new vectors x and y, which conta**in**s respectively cos**in**e ands**in**e to the t-values.We will know try to plot more than one graph **in** the same w**in**dow us**in**g thecommand hold on:• Plot the graph **for** cos(t) us**in**g the vectors t and x.• Type hold on (I won’t write press ‘enter’ aga**in**, but it should of coursebe done after each command).• Plot the graph **for** s**in**(t) us**in**g the vectors t and y.• Type plot(x,y). What happens?To ‘undo’ a hold on one has to use the command hold off. This ensuresthat the next graph is plotted by itself. Try it, and do plot(x,y) aga**in**.Use the help system to f**in**d how to use the follow**in**g commands:• axis. Try to scale the last graph so that it looks like a circle.• title• gtext• xlabel and ylabel• whos• clear

8 CHAPTER 1. INTRODUCTION TO MATLAB1.3 Scripts **in** MatLabAs mentioned you can write your own programs **in** MatLab. This can be done**in** **for**m of a so-called ‘script’, which is a collection of MatLab commands put**in**to a file, called an ‘M-file’. To start mak**in**g a script open an editor-w**in**dow:Go **in**to the menu ‘File’, choose ‘new’, and then ‘M-file’. This opens an editorw**in**dow where you can write a MatLab script.To run a script it needs to have a name of the **for**m name.m and be stored**in** a directory where MatLab can f**in**d it. This can **for** example be the currentdirectory, i.e. the script should be visible if you execute the command ls• Type **in** the follow**in**g script:x=-3:0.1:3;**for** b=-5:1:5y=x.^2-b*x-1;plot(x,y)hold onend• Save the script under a suitable name, and run it. To run a script **in**MatLab you simply type the name of the script on the command l**in**e andpress ‘Enter’. For technical reasons it sometimes happens that MatLabreports an error say**in**g that it cannot f**in**d the file even though you justsaved it. If that happens, do the follow**in**g:– Check that you are **in** the right directory by typ**in**g ls. If your scriptis listed you are **in** the right directory. If not, use the command cdto f**in**d the right directory.– When you are sure you are **in** the right directory use the commandaddpath . (**in**clud**in**g the period). This command tells MatLab tocheck the files **in** the current directory• Expla**in** the graphical w**in**dow that appears when you run your script• Expla**in** what the **in**dividual commands **in** the script mean. It is especiallyimportant that you understand the command **for**. This **in**dicates the startof a so-called **for**-loop, which is term**in**ated by end. This command is usedoften later **in** the course, so you should use the help system to f**in**d outhow it works.

Chapter 2Equations of motion withvariable **for**ceSource: Ohanian: “**Physics**”, 2. ed. exp., W.W. Norton & Company (1989).In this web version of “**Notes** **for** **Supplementary** **Course** **in** **Physics**”, we cannot**in**clude the pages from Ohanian **for** copyright reasons.9

10 CHAPTER 2. EQUATIONS OF MOTION WITH VARIABLE FORCE.

.11

12 CHAPTER 2. EQUATIONS OF MOTION WITH VARIABLE FORCE.

.13

14 CHAPTER 2. EQUATIONS OF MOTION WITH VARIABLE FORCE.

.15

16 CHAPTER 2. EQUATIONS OF MOTION WITH VARIABLE FORCE

Chapter 3Numerical solution ofequations of motionIn this chapter we learn how to do numerical solution of equations of motion.The start**in**g po**in**t **for** this is Chapter 2 **in** these notes, “Equations of motionwith variable **for**ce.”The equations of motion we have worked with **in** the course so far have beenespecially nice and well behaved. In fact we have been able to solve all of themanalytically, i.e. with pen and paper. However, **in** the real world th**in**gs arenot always so simple. In fact, **in** most cases the equations of motion cannot besolved analytically, and one has to solve them by numerical methods. This iscalled simulation, and us**in**g Matlab to do this is the subject of this chapter.3.1 Euler’s methodThe numerical method discussed **in** the previous chapter is called Euler’s method.It is named after the Swiss mathematician Leonhard Euler (1707-1783). In thissection we will see how Euler’s method can be implemented (programmed) **in**MatLab.As a start**in**g po**in**t **for** us**in**g the method, one needs to know• t 0 - the time at which the simulation starts (often set to zero)• x 0 - the **in**itial position, i.e. the position at time t 0• v 0 - the **in**itial velocity, i.e. the velocity at time t 0This **in****for**mation as a whole is called “the **in**itial conditions.” Furthermore, oneneeds to know the **for**ce on the particle. In general the **for**ce on the particle candepend on the position, the velocity, and/or the time. When the **for**ce is known,17

18CHAPTER 3.NUMERICAL SOLUTION OF EQUATIONS OF MOTIONone can via Newton’s second law f**in**d the acceleration: a = F/m, where m isthe mass of the particle.Given the **in****for**mation mentioned above, one can calculate the correspond**in**gvalues a time step ∆t later (**for** simplicity we assume that the **for**ce and therebythe acceleration only depend on the position)t 1 = t 0 + ∆t (3.1)x 1 = x 0 + v 0 · ∆t (3.2)v 1 = v 0 + a(x 0 ) · ∆t (3.3)Given the values after the first time step, we can repeat this process to f**in**dvalues at different times, and, **in** general we can writet i+1 = t i + ∆t (3.4)x i+1 = x i + v i · ∆t (3.5)v i+1 = v i + a(x i ) · ∆t (3.6)These equations correspond to equations 27, 32 and 33 **in** the previous chapter(with F (x) = −A/x 2 , A = 1.0, and m = 1.0).It is important to understand, that one is mak**in**g a small error every timeEuler’s method is used to calculate a new time step. This can be seen, **for**example, by not**in**g that equation 3.5 is equivalent tov i = x i+1 − x i∆t(3.7)which clearly is only an approximation of the **in**stantaneous velocity (v ≡ dx/dt).The magnitude of the error is **in** general dependent on the time step, ∆t; asmaller ∆t leads to a smaller error.Usually one wants to calculate the positions, x(t), and the velocities, v(t), toa given precision **in** a given time **in**terval. How do we f**in**d out if the simulationis precise enough? This is easy if we know the analytical solution: we justcompare the simulation to the analytical result. In fact, one should always testthe program on a system where we do know the analytical result. However thereason **for** do**in**g a simulation is that we usually have a problem that we don’tknow the analytical solution to. In that case one can do the follow**in**g: Makea simulation with the time step ∆t and another simulation with the time step∆t/2. Now, compare the two results: If they are identical to the precision wewant, then we are done and we can trust the results. If the results are notsimilar enough, we try aga**in** with even smaller time steps.Even **for** simple equations of motion, Euler’s method requires a lot of calculations,and it is there**for**e only practical if a computer is used to do the calculations.The Matlab script below implements Euler’s method **for** the exampleused **in** Chapter 1 (F (x) = −A/x 2 , A = 1.0 and m = 1.0):

3.1. EULER’S METHOD 19tstart=0;tend=5 ;x=1.0;v=1.0;n=25;% Initial time% F**in**al time% Initial position% Initial velocity% Number of stepsttable = zeros(1,n+1); % Tables are **in**itialized **for**: t (time)xtable = zeros(1,n+1); %x (positions)vtable = zeros(1,n+1); %v (velocities)dt = (tend-tstart)/n; % Compute timestept=tstart;ttable(1)=t;xtable(1)=x;vtable(1)=v;% Put **in**itial conditions **in** tables**for** i=2:1:n+1t = t+dt;a = -1./x.^2;x = x+v*dt;v = v+a*dt;ttable(i) = t;xtable(i) = x;vtable(i) = v;end;% Update the time% Calculate acceleration% Update the position% Update the velocity% The calculated values of t, x and v% are stored **in** the tables.plot(ttable,xtable) % Plot the calculated trajectoryExercise Type this program **in** the Matlab editor, and save it under aappropriate name (‘Euler’ cannot be used s**in**ce Matlab already has a functionwith that name). Run the program and compare the results with the example **in**the previous chapter - the results should be identical. Go through the programand make sure you understand the mean**in**g of each l**in**e. Investigate how manytime steps (n) are needed to get a satisfy**in**g solution of the equations of motion.Exercise Modify the program so that the **for**ce is a spr**in**g-**for**ce (save theprogram under a new name, us**in**g the menu item ‘save as’). Use **for** examplethe **in**itial conditions x 0 = 1, v 0 = 0. Compare your results with the analyticalsolution. What happens if you let the simulation run over several periods?(Remember to change the number of time steps (n) so that the length of thetime step (dt) is the same .) What is the problem? (Try mak**in**g a plot of thevelocities versus the positions.)

20CHAPTER 3.NUMERICAL SOLUTION OF EQUATIONS OF MOTION3.2 The Leap-Frog methodThe problem with Euler’s method is **for**tunately easily solved. If we look atequation 3.7, this can be **in**terpreted as we are us**in**g the average velocity **in**the time **in**terval between i and i+1 as an approximation of the **in**stantaneousvelocity at time t i . It seems logical (and can be shown) that the expression onthe right side of equation 3.7 is a better approximation **for** the **in**stantaneousvelocity **in** the middle of the time **in**terval (which we here will call v i+ 1 ):2v i+ 12= x i+1 − x i∆t⇔ (3.8)· ∆t (3.9)x i+1 = x i + v i+ 12In similar manner we can write the acceleration:a i = v i+ 1 − v 2 i− 1 2∆tv i+ 12⇔ (3.10)= v i− 12 + a i · ∆t (3.11)We have now developed the so-called “Leap-Frog” method, which can bewritten:t i+1 = t i + ∆t (3.12)v i+ 12= v i− 1 i · ∆t2(3.13)· ∆t (3.14)x i+1 = x i + v i+ 12Note that the velocity is updated be**for**e the position. Why?To start up the “Leap-Frog” method we need to know v 0− 1 = v 2 − 1 , i.e. the2velocity half a time step be**for**e t = 0. However, normally one prefers to givethe velocity at t = 0 as the **in**itial condition. This can be done by us**in**g thefollow**in**g equation:v − 12= v 0 − 1 2 · a x(0) · ∆t (3.15)This corresponds to tak**in**g half a time step backwards with respect to the velocity.It is easy to modify the Matlab program so that it uses the “Leap-Frog”method **in**stead of the Euler method. Only two changes are needed:• Two l**in**es are added after the calculation of the time step:1. a=...; i.e. calculate the acceleration from the **in**itial conditions.2. v = v-.5*a*dt; i.e. take a half a step backwards accord**in**g to equation3.15.

3.2. THE LEAP-FROG METHOD 21• Exchange the two l**in**es **in** the **for**-loop where x and v are updated (makesure you understand why this is done):v=v+a*dt;x=x+v*dt;Exercise Modify your Matlab program so that it uses the Leap-Frog method.Is it now better at solv**in**g the equations of motion **for** the spr**in**g? Comparewith the analytical solution.Exercise Add friction to your spr**in**g. E.g. imag**in**e that the object at theend of the spr**in**g slides on a table with the (dynamical) friction coefficient µ.(H**in**t: You might need to use the function, sign). What effect does the frictionhave?Exercise Modify your Matlab program so that it can simulate a spr**in**g(without friction) **in** two dimensions, i.e. F x = −k · x and F y = −k · y Thusthe program needs to keep track of the x- and y-coord**in**ates, and the x- andy-components of the velocity. Can you set up the **in**itial conditions so that themotion becomes a circle? (Try: plot(xtable,ytable).)

22CHAPTER 3. NUMERICAL SOLUTION OF EQUATIONS OF MOTION

Chapter 4Matlab commandsThis chapter conta**in**s lists of commands and functions often used **in** Matlab.The descriptions **in**cluded here are very brief - to get more help you should usethe help system **in** MatLab (e.g. help xlabel). Further help can be foundhere: http://**dirac**.ruc.dk/SuppPhys09/Matlab.html4.1 Simple mathematical functionsSimple mathematical functions works the way one would expect **in** MatLab. Ifx is an vector or matrix the functions listed below are applied to each element**in** x and the result is a vector or matrix with the same size as x.• cos(x), cos**in**e x (**in** radians).• s**in**(x), s**in**e x (**in** radians).• tan(x), tangent x (**in** radians).• acos(x), **in**verse cos**in**e x. b = acos(x) ⇒ x = cos(b).• as**in**(x), **in**verse s**in**e x. b = as**in**(x) ⇒ x = s**in**(b).• atan(x), **in**verse tangent x. b = atan(x) ⇒ x = tan(b).• exp(x), the exponential function.• log(x), the natural logarithm. b = log(x) ⇒ x = exp(b).• log10(x), base 10 logarithm. b = log 10 (x) ⇒ x = 10 b .• sqrt(x), square root. b = sqrt(x) ⇒ x = b 2 .• floor(x), round**in**g down. floor(3.4) = 3.• ceil(x), round**in**g up. ceil(3.4) = 4.23

24 CHAPTER 4. MATLAB COMMANDS• round(x), round to nearest **in**teger. round(3.4) = 3.• rem(x,b), rem**in**der after **in**teger division. rem(13, 5) = 3. (13 = 2∗5+3).• sign(x), sign of x. sign(3) = 1, sign(−4) = −1, sign(0) = 0.4.2 Other mathematical functionsBelow it is assumed that x is an vector.• mean(x), mean of the elements **in** x.• sum(x), sum of the elements **in** x.• cumsum(x), accumulated sum of the elements **in** x.• max(x). largest element **in** x.• m**in**(x). smallest element **in** x.4.3 Mathematical operators• z=x.*y . multiplication of elements:must have identical size.z(i,j) = x(i,j)*y(i,j); Note: x and y• z=x./y . division of elements:have identical size.z(i,j) = x(i,j)/y(i,j); Note: x and y must• x.^b . rais**in**g the elements **in** x to the power b. x.^(1/2) is identical tosqrt(x).• a:b:c , generation of a vector with the numbers from a to c, with the stepsize b between the numbers.• [a b c d] , another way of generat**in**g a vector. The generated vectorconta**in**s the numbers a, b, c and d.

4.4. GRAPHICS 254.4 Graphics• plot(x,y, ’.-’). Plot the data **in** x and y, as po**in**ts connected withstraight l**in**es.• plot(x1,y1, ’.-’,x2,y2). Plot two graphs **in** the same plot.• semilogx(x,y, ’.-’). Plot the data **in** x and y, with a logarithmic x-axis.• semilogy(x,y, ’.-’). Plot the data **in** x and y, with a logarithmic y-axis.• loglog(x,y, ’.-’).Plot the data **in** x and y, with a logarithmic x- andy-axis.• axis([x1 x2 y1 y2]). Scale the plot, so that the x-axis goes from x1 tox2 and the y-axis from y1 to y2.• axis equal. Impose identical scal**in**g on the two axis.• title( ’This is a graph’). Put a title on the plot.• xlabel( ’time’). Put a label on the x-axis.• ylabel( ’position’). Put a label on the y-axis.• gtext( ’This is a text’).mouse).Put a text **in** the graph (placed by the• hold on. Plot the follow**in**g graphs on top of the exist**in**g.• hold off. Erase old graphs when a new plot is made.• figure. Make a new graphics w**in**dow.4.5 Program structure• **for**. **for**-loop (ends with a end).**for** i=1:1:10command1;command2;iend;The commands between **for** and the correspond**in**g end are executed once**for** each value of the **in**dex-variable, which is here i. The **in**dex variablecan be used **in**side the loop. In this example the numbers from 1 to 10will be pr**in**ted **in** the command w**in**dow one at a time.

26 CHAPTER 4. MATLAB COMMANDS• if. Execute the follow**in**g piece of code only if a given condition is fulfilled.if a>0command1;command2;end;The commands between if and end are executed only if a > 0.4.6 Miscellaneous• help command . Gives help regard**in**g the MatLab-command command.• cd. “Change Directory”.• pwd. “Pr**in**t Work**in**g Directory”.• ls. List the files **in** the present directory.• dir. List the files **in** the present directory.• addpath . (Includ**in**g the period). Makes MatLab update its **in****for**mationson the present directory. This is sometimes necessary if MatLabclaims that a file (e.g. a script or function) is not **in** the directory.• whos. Lists all variables• save -ascii filename variable. Saves the variable variable **in** thefile filename.• load -ascii filename. Loads the data **in** the file filename and storesit **in** a variable with the same name (unless it conta**in**s periods or similarcharacters).• size(x). Returns the number of rows and columns **in** the variable x.• length(x). Returns the number of elements **in** the vector x.• clear variable. Erases the variable variable from the memory.• clear. Erases all variables from the memory.