Docsity

Learning Programming with Matlab: A Student's Guide, Assignments of Physics

Toggle sidebar
bg1
Physics PHY-4151, fall semester 2008
How to Program
People have different ideas of how to teach programming. I understand that many
computer-science departments, treating it as an academic discipline, take a systematic ap-
proach, starting with Alan Turing’s theory of computation, continuing with a survey of
hardware, then data structures, and finally the various constructs in a program. The draw-
back to this approach is that it takes four years.
The way I learned to program was simpler: while in junior high school, I picked up a
manual and read the technical descriptions of the commands, in alphabetical order. During
the rest of high school, I played around on the school computer and on an Apple ][, writing
programs to do various things, mostly games of my own invention. I had no guidance,
because none of the teachers did much programming. At that time, each school had one
computer, so it wasn’t part of the curriculum. However, there was no commercial software
and no Internet, so the only way to make a computer do anything was to write a program.
The drawback to this approach is that it, too, takes four years.
The two foregoing paragraphs make programming sound much too hard to learn. It isn’t,
really. A program is a set of instructions, which the computer follows in order. Since people,
not computers, designed the languages that computers understand, it becomes fairly easy,
with a little practice, to figure them out. The approach this course will take is to present a
problem, then show how to use Matlab/Octave to solve it.
Suggestion for how to learn to program:
1. Have a task to do.
2. Don’t know how to make the computer do it, so
3. Compare to examples, or
4. Look it up in Pratap or another Matlab reference, or
5. Ask a friend, or
6. Ask the instructor.
7. Don’t be afraid of trying things. You can type random, wrong commands for a hundred
years, and you still won’t break anything.
There is no homework to turn in for the week of 1 September; instead, we’ll
work through the exercises in this handout. Each subsequent week, there will be a
homework exercise, usually due at midnight between Sunday and Monday.
1. Using Matlab/Octave as a calculator
Say you’re a pre-med student, and you left your calculator home. You have to add 2+2
and can’t remember the answer. Instead of panicking, you pull up Matlab. In this example,
what the computer types will be in italics and what you type in typewriter font.
physics.cas.usf.edu % matlab0
<M A T L A B >
Copyright 1984-2007 The MathWorks, Inc.
1
pf3
pf4
pf5
pf8

Partial preview of the text

Download Learning Programming with Matlab: A Student's Guide and more Assignments Physics in PDF only on Docsity!

Physics PHY-4151, fall semester 2008 How to Program

People have different ideas of how to teach programming. I understand that many computer-science departments, treating it as an academic discipline, take a systematic ap- proach, starting with Alan Turing’s theory of computation, continuing with a survey of hardware, then data structures, and finally the various constructs in a program. The draw- back to this approach is that it takes four years.

The way I learned to program was simpler: while in junior high school, I picked up a manual and read the technical descriptions of the commands, in alphabetical order. During the rest of high school, I played around on the school computer and on an Apple ][, writing programs to do various things, mostly games of my own invention. I had no guidance, because none of the teachers did much programming. At that time, each school had one computer, so it wasn’t part of the curriculum. However, there was no commercial software and no Internet, so the only way to make a computer do anything was to write a program. The drawback to this approach is that it, too, takes four years.

The two foregoing paragraphs make programming sound much too hard to learn. It isn’t, really. A program is a set of instructions, which the computer follows in order. Since people, not computers, designed the languages that computers understand, it becomes fairly easy, with a little practice, to figure them out. The approach this course will take is to present a problem, then show how to use Matlab/Octave to solve it.

Suggestion for how to learn to program:

  1. Have a task to do.
  2. Don’t know how to make the computer do it, so
  3. Compare to examples, or
  4. Look it up in Pratap or another Matlab reference, or
  5. Ask a friend, or
  6. Ask the instructor.
  7. Don’t be afraid of trying things. You can type random, wrong commands for a hundred years, and you still won’t break anything. There is no homework to turn in for the week of 1 September; instead, we’ll work through the exercises in this handout. Each subsequent week, there will be a homework exercise, usually due at midnight between Sunday and Monday.
  8. Using Matlab/Octave as a calculator

Say you’re a pre-med student, and you left your calculator home. You have to add 2 + 2 and can’t remember the answer. Instead of panicking, you pull up Matlab. In this example, what the computer types will be in italics and what you type in typewriter font.

physics.cas.usf.edu % matlab

< M A T L A B > Copyright 1984-2007 The MathWorks, Inc.

Version 7.4.0.336 (R2007a) January 29, 2007

To get started, type one of these: helpwin, helpdesk, or demo. For product information, visit www.mathworks.com.

2+ ans = 4

After typing a command (e.g., matlab0), you need to hit the carriage-return (sometimes called “enter”) key. Octave is a free program that is mostly compatible with Matlab. Type exit to get out of Matlab, or try it in a second terminal window:

physics.cas.usf.edu% octave GNU Octave, version 2.1.57 (i686-pc-linux-gnu). Copyright (C) 2004 John W. Eaton. This is free software; see the source code for copying conditions.

octave:1> 2+ ans = 4

Exercise. Calculate 2

  1. Multiplication, with the * operator, needs to be explicit. Square root is implemented as a function, sqrt().
  2. Can the computer remember an intermediate result?

You can assign an intermediate result to a named variable, then recall the value of the variable later:

x = 2+ x = 4 2+x ans = 6

Exercise. As an equation, the following makes no sense. Find out what it actually does: x = x + 1 Exercise. Variable names can have more than one letter, but can they include digits? Spaces? Special characters? Figure out by trial and error what restrictions there are on

speed of 2.0 m/s. (It’s always a good idea with a computer to start off with a problem one can check in one’s head before moving on to harder problems.) If you try to enter symbols like kg and m/s, you will be dismayed to discover that Matlab knows nothing about units. This is a general problem with numerical computation and was directly responsible for the loss of NASA’s Mars Climate Orbiter in 1999: one set of engineers were using centimeters, while another set of engineers thought they were using inches. Of course, it’s no different with a calculator. It is the responsibility of the person doing the calculation to write clear notes explaining what units are in use.

0.51.52.0^ ans = 3

This works, but the book where I got the problem has one hundred more just like it except with different numbers. It would save time if I could use a function similar to sqrt() or sin(), which we’ve already seen. I’d like to have the following work:

energy(1.5,2) ans = 3

Not only can I make it work; I can also write documentation so that the built-in Mat- lab/Octave help command knows about it:

help energy ENERGY -- given mass and velocity, calculate energy DAR 8/25/

usage: e = energy(m, v)

where m is mass and v velocity. The value (e) returned is the kinetic energy

Use the non-relativistic formula e=0.5mv^.

To do this, we need to create a file called energy.m in the directory where we’re working. I’ll spend time in class on Unix directories, files, and editors; this is the point where you need to be able to use them. The following file serves the purpose (in either Matlab or Octave): % ENERGY -- given mass and velocity, calculate energy % DAR 8/25/ % % usage: e = energy(m, v) % % where m is mass and v velocity. The value (e) returned % is the kinetic energy % % Use the non-relativistic formula e=0.5mv^.

function e = energy(m, v) e = 0.5 * m * v^2; % this returns the energy

A few notes: the file implementing energy must be called energy.m. Also, notice that the words following a percent (%) sign are ordinary English. Matlab ignores them. Whatever the computer language, these comments are the most important part of any computer pro- gram: if they are well organized, a good programmer can reproduce the rest of the program from the comments alone. Conversely, imagine a 1,000,000-line code with no comments or documentation. It might take a team of computer archeologists a year to figure out what the code does. Matlab knows to print the comments at the beginning of the file when asked for help. It’s useful to the reader for these comments to specify the name of the function, its purpose, who wrote it, when, how to call it, what its arguments (m and v) mean, what it returns, and how it works.

Exercise. Check a few more values of mass and velocity to make sure there isn’t a bug.

Exercise. Make a new program, called renergy.m, that returns the relativistic kinetic energy, mc^2 √ 1 − v^2 /c^2

− mc^2 , (1)

where m is mass, c = 2.9979E08 m/s, and v is velocity. (Note that 2.9979E08 is how Matlab displays the number 2. 9979 × 108 .) Your comments should note that m and v have to be entered in SI units (the same did not apply to energy(): why not?). Algebraically, (1) reduces to (1/2)mv^2 for v ≪ c, but unless you’ve been clever at converting (1) to code, you will find that, numerically, renergy() gives the wrong answer for small velocities. Why? The field of numerical analysis finds ways around problems like this. (You’re not required to figure this out right now, but you could start with a Taylor series if you’re looking for something to do.)

Exercise. See if you can “break” renergy() by feeding it unphysical values.

  1. Are variables inside functions the same as variables outside?

To answer this question, make the following vtest.m file: % VTEST -- test the connection between variables inside & outside a function % DAR 8/25/ % % usage: r = vtest(a, b, c) % % Return (in r) the number a + b - c. % Implementation: a little weird so we can check things out.

function r = vtest(a, b, c) x = a + b; % get an intermediate result first x = x - c; % now subtract c from the intermediate result r = x; % and return it

% usage: f = fact2(n) % % Return n! if n is an integer bigger than or equal to 0. % Otherwise, give an error message.

function f = fact2(n)

% Check for errors. if( fix(n)~=n || n<0 ) error(’%d is not a non-negative integer’, n) % aborts fact2() end

% Calculate recursively. if( ~n ) % same as n== f = 1; else f = n*fact2(n-1); end

Exercise. Understand these two programs. You don’t have to type them in; they’re in the directory /home/4151/examples/week1. Copy them from there to your directory.

  1. The Fibonacci sequence

Leonardo of Pisa (c.1170–c.1250), known as Fibonacci, developed the sequence of num- bers F 1 = 1 F 2 = 1 F 3 = 2 F 4 = 3 F 5 = 5 F 6 = 8

... Fn = Fn− 1 + Fn− 2

in a simplified model of rabbit reproduction. Fibonacci started with a single small (S) rabbit, S , which grew up to be a large (L) rabbit, L. The large rabbit reproduced asexually (this had to get through the 13th-century censors) to give rise to a small rabbit, LS , which in the next generation grew up to become a large rabbit. In the meantime, its parent

produced another small rabbit: LSL. You can guess what comes next: LSLLS.

Exercise. Convince yourself that the number of rabbits in the nth^ generation is Fn as given by (2).

More recently, Dan Shechtman discovered in 1982 a new class of intermetallic alloys called quasiperiodic crystals or quasicrystals for short.^1 These materials are characterized by long-range order, as evidenced by x-ray and electron diffraction patterns, and perfect crystallographically forbidden symmetries, such as 5-fold axes, meaning that the crystal looks the same after being rotated 72◦. Because 5-fold symmetry is incompatible with periodicity (as noted by, among others, Johannes Kepler), for two hundred years it was believed that such materials could not exist. Many authors have found in atomic-force microscopy and scanning-tunneling microscopy of quasicrystals surface motifs with long (L) and short (S) distances corresponding to Fibonacci’s sequence of rabbits. See, for example, Schaub et al., Phys. Rev. Lett. 73 , 1255–1258 (1994). On physics, you can bring this paper up with the command

physrev L 73 1255.

Exercise. Using the loop strategy from the previous section, write a function fib(n) that will return Fn.

Exercise. Using the recursive strategy from the previous section, write a function fib2(n) that will return Fn.

Exercise. You may be familiar with a clever application of 2 × 2 matrices that makes it possible to calculate the nth^ Fibonacci number directly, without using loops or recursion. Implement this strategy. (The programming is easier, but first you have to work through the math.)

Exercise. Plot a graph of Fn against n. Once you get this working, figure out how to plot just ×’s, suppressing the connecting of the dots.

(^1) D. Shechtman, I. Blech, D. Gratias, J.W. Cahn, Phys. Rev. Lett. 53 , 1951–1953 (1984).