Notes for Supplementary Course in Physics, 2010Thomas Schrøder, updated by N. BaileySeptember 1, 2010
Contents1 Introduction to MatLab 51.1 What is MatLab? . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.3 Scripts in MatLab . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Equations of motion with variable force 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
Chapter 1Introduction to MatLab1.1 What is MatLab?MatLab is an interactive program for numerical computation and data visualization.There are many different toolboxes available which extend the basicfunctions of MatLab into different application areas. This is a short guide to thebasic features of MatLab and designed to give you an introduction to MatLab.The text is intended for you to sit down in pairs in front of the computer, andgo through the exercises in the text.1.2 Getting startedBefore you get started it is important that you have an understanding 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 organizedin 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 windows-based program. There are 3 different kinds of windows:the command window, where you control the calculations, graph windows (figures)and editor windows, where you can write, save and load programs forMatLab (m-files).To get started just double-click on the MatLab icon on your screen and thecommand window will appear.• Start MatLab.When MatLab is started the command window will appear and you cantype commands after the >>5
6 CHAPTER 1. INTRODUCTION TO MATLAB• Type pwd (Print Working Directory) and MatLab will return the current(working) directory. If this is not H:, you should change directory to H:by typing cd H: (cd stands for ‘change directory’). Try the command pwdagain.• Now, if you want to make a subdirectory type: mkdir name (mkdir standsfor ‘make directory’). You change the working directory to this subdirectoryby typing cd name.Important: Every time you start MatLab you should make sure you areworking in the right directory!• Type x=0:1:10; on the command-line 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 points 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 information 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 window, and then zoom using the mouse.Try it!You have now experienced a important strength of MatLab: It can do computationswith vectors, which means you with a single command can do mathematicaloperations on hundreds or thousands of numbers at once (all the elementsin the vector). You can get a single number out of a vector, if you typex(10) where x is the name of the vector and 10 is the ‘index’ stating whatelement in the vector you are interested in.• What is the index of the first number in a vector?
1.2. GETTING STARTED 7• Plot a graph of the line given by y = 2x + 4.• Plot a graph of the line 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 interprets x as a ‘matrix’ (i.e. twodimensionaltable with numbers) and * is interpreted as a so-called matrixmultiplication.We don’t use these kind of calculations in this course.If you instead 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 corresponding 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 interval.• Do an graphical estimate of the roots of the equation above (i.e. findthe x-values for which y = 0). Compare your solutions to the analyticalsolution. Hint: 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 contains respectively cosine andsine to the t-values.We will know try to plot more than one graph in the same window using thecommand hold on:• Plot the graph for cos(t) using the vectors t and x.• Type hold on (I won’t write press ‘enter’ again, but it should of coursebe done after each command).• Plot the graph for sin(t) using 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) again.Use the help system to find how to use the following 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 donein form of a so-called ‘script’, which is a collection of MatLab commands putinto a file, called an ‘M-file’. To start making a script open an editor-window:Go into the menu ‘File’, choose ‘new’, and then ‘M-file’. This opens an editorwindow where you can write a MatLab script.To run a script it needs to have a name of the form name.m and be storedin a directory where MatLab can find it. This can for example be the currentdirectory, i.e. the script should be visible if you execute the command ls• Type in the following 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 inMatLab you simply type the name of the script on the command line andpress ‘Enter’. For technical reasons it sometimes happens that MatLabreports an error saying that it cannot find the file even though you justsaved it. If that happens, do the following:– Check that you are in the right directory by typing ls. If your scriptis listed you are in the right directory. If not, use the command cdto find the right directory.– When you are sure you are in the right directory use the commandaddpath . (including the period). This command tells MatLab tocheck the files in the current directory• Explain the graphical window that appears when you run your script• Explain what the individual commands in the script mean. It is especiallyimportant that you understand the command for. This indicates the startof a so-called for-loop, which is terminated by end. This command is usedoften later in the course, so you should use the help system to find outhow it works.
Chapter 2Equations of motion withvariable forceSource: Ohanian: “Physics”, 2. ed. exp., W.W. Norton & Company (1989).In this web version of “Notes for Supplementary Course in Physics”, we cannotinclude the pages from Ohanian for copyright reasons.9
10 CHAPTER 2. EQUATIONS OF MOTION WITH VARIABLE FORCE.
12 CHAPTER 2. EQUATIONS OF MOTION WITH VARIABLE FORCE.
14 CHAPTER 2. EQUATIONS OF MOTION WITH VARIABLE FORCE.
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 starting point for this is Chapter 2 in these notes, “Equations of motionwith variable force.”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 things 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 using 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) inMatLab.As a starting point for using the method, one needs to know• t 0 - the time at which the simulation starts (often set to zero)• x 0 - the initial position, i.e. the position at time t 0• v 0 - the initial velocity, i.e. the velocity at time t 0This information as a whole is called “the initial conditions.” Furthermore, oneneeds to know the force on the particle. In general the force on the particle candepend on the position, the velocity, and/or the time. When the force is known,17
18CHAPTER 3.NUMERICAL SOLUTION OF EQUATIONS OF MOTIONone can via Newton’s second law find the acceleration: a = F/m, where m isthe mass of the particle.Given the information mentioned above, one can calculate the correspondingvalues a time step ∆t later (for simplicity we assume that the force 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 findvalues 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 making a small error every timeEuler’s method is used to calculate a new time step. This can be seen, forexample, by noting that equation 3.5 is equivalent tov i = x i+1 − x i∆t(3.7)which clearly is only an approximation of the instantaneous 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 interval. How do we find 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 doing a simulation is that we usually have a problem that we don’tknow the analytical solution to. In that case one can do the following: 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 again with even smaller time steps.Even for simple equations of motion, Euler’s method requires a lot of calculations,and it is therefore 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% Final time% Initial position% Initial velocity% Number of stepsttable = zeros(1,n+1); % Tables are initialized 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 initial conditions in tablesfor 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 since Matlab already has a functionwith that name). Run the program and compare the results with the example inthe previous chapter - the results should be identical. Go through the programand make sure you understand the meaning of each line. Investigate how manytime steps (n) are needed to get a satisfying solution of the equations of motion.Exercise Modify the program so that the force is a spring-force (save theprogram under a new name, using the menu item ‘save as’). Use for examplethe initial 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 making 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 fortunately easily solved. If we look atequation 3.7, this can be interpreted as we are using the average velocity inthe time interval between i and i+1 as an approximation of the instantaneousvelocity 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 instantaneousvelocity in the middle of the time interval (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 before 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 before t = 0. However, normally one prefers to givethe velocity at t = 0 as the initial condition. This can be done by using thefollowing equation:v − 12= v 0 − 1 2 · a x(0) · ∆t (3.15)This corresponds to taking 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 instead of the Euler method. Only two changes are needed:• Two lines are added after the calculation of the time step:1. a=...; i.e. calculate the acceleration from the initial conditions.2. v = v-.5*a*dt; i.e. take a half a step backwards according to equation3.15.
3.2. THE LEAP-FROG METHOD 21• Exchange the two lines 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 solving the equations of motion for the spring? Comparewith the analytical solution.Exercise Add friction to your spring. E.g. imagine that the object at theend of the spring slides on a table with the (dynamical) friction coefficient µ.(Hint: You might need to use the function, sign). What effect does the frictionhave?Exercise Modify your Matlab program so that it can simulate a spring(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-coordinates, and the x- andy-components of the velocity. Can you set up the initial conditions so that themotion becomes a circle? (Try: plot(xtable,ytable).)
22CHAPTER 3. NUMERICAL SOLUTION OF EQUATIONS OF MOTION
Chapter 4Matlab commandsThis chapter contains lists of commands and functions often used in Matlab.The descriptions included 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 elementin x and the result is a vector or matrix with the same size as x.• cos(x), cosine x (in radians).• sin(x), sine x (in radians).• tan(x), tangent x (in radians).• acos(x), inverse cosine x. b = acos(x) ⇒ x = cos(b).• asin(x), inverse sine x. b = asin(x) ⇒ x = sin(b).• atan(x), inverse 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), rounding down. floor(3.4) = 3.• ceil(x), rounding up. ceil(3.4) = 4.23
24 CHAPTER 4. MATLAB COMMANDS• round(x), round to nearest integer. round(3.4) = 3.• rem(x,b), reminder after integer 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.• min(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 . raising 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 generating a vector. The generated vectorcontains the numbers a, b, c and d.
4.4. GRAPHICS 254.4 Graphics• plot(x,y, ’.-’). Plot the data in x and y, as points connected withstraight lines.• 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 scaling 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 following graphs on top of the existing.• hold off. Erase old graphs when a new plot is made.• figure. Make a new graphics window.4.5 Program structure• for. for-loop (ends with a end).for i=1:1:10command1;command2;iend;The commands between for and the corresponding end are executed oncefor each value of the index-variable, which is here i. The index variablecan be used inside the loop. In this example the numbers from 1 to 10will be printed in the command window one at a time.
26 CHAPTER 4. MATLAB COMMANDS• if. Execute the following 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 regarding the MatLab-command command.• cd. “Change Directory”.• pwd. “Print Working Directory”.• ls. List the files in the present directory.• dir. List the files in the present directory.• addpath . (Including the period). Makes MatLab update its informationson 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 contains 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.