This site is aimed at math and physics majors who may have little programming experience, but who want to learn techniques in computational physics. It contains examples pulled from a variety of fields in math, physics and astronomy. The examples are meant to supplement existing tutorials such as the excellent one put together by Spencer and Ware at BYU. It may be downloaded in pdf form from their website here.  

Programming Basics

First Steps
Example Description Commands
A00 Hello World – As simple as it gets. disp()
A01 Hello World: The Fancy Version – adds housekeeping commands. clc, clear, close all
A02 Period of a Pendulum – Prompt user for input and use the info in a simpe calculation. Display the result in a nicely-formated way. input(), fprintf()
A03 Fine Structure Constant – Read in a file containing previously defined variables (fundamental constants) and use them in a simple calculation. load()
Loops and If Statements
Example Description Commands
A04 Summing the Integers – Demonstrates use of a for loop for loop
A04B Nested for loops for loop
A05 Taylor Series – Use for loop to add up the terms in a Taylor series expansion of cos(x) for loop
A06 Making Loops Go Faster – Tricks to increase computation speed including preallocating arrays and using built-in Matlab functions. tic, toc, sum()
A07 Approximating pi – Use a while loop to calculate pi to a desired accuracy. while loop
A08 Guessing Game – Demonstrates use of an if statement to compare two numbers. if statement
A09 Approximating pi (part 2) – Use a for loop and a break statement to calculate pi to a desired accuracy. for loop, break
A10 First N prime numbers – Combine a while loop with an if statement. while loop, if statement
Reading Data Files
Example Description Commands
A11 Read in data from an ASCII file load(), textread()
Download all Programing Basics Examples A00.m–A11.m here.



2D Plots
Example Description Commands
plot01 Simple line plots. Options for specifying line and marker colors and styles. plot()
plot02 Axis limits. Plot y=sin(x) xlim(), ylim(), axis()
plot03 Annotations and Greek symbols. length(), text()
plot04 Printing and saving PDF, JPEG, Tiff figures. set(), print()
plot05 Graphing two or more things on the same plot. plot()
plot06 Graphing two or more things on the same plot using hold all. hold all, hold off
plot07 Overlaying a sine function on noisy data hold all
plot08 Putting Multipe Plots on One Page subplot()
plot09 Parametric Plots: Lissajous Figures plot()
plot10 Grid of Lissajous Figures plot(), subplot()
Download all 2D Plot Examples plot01.m–plot10.m here.



Solving Ordinary Differential Equations (ODEs)

Celestial Mechanics

Home   |   Plot Thumbnails