Professional Documents
Culture Documents
MatlabSession1 PHAS2441
MatlabSession1 PHAS2441
Contents
1. Aims and objectives 1
2. A review of Matlab 1
2.1. Simple matrix operations, 1.2.2. Visualizing data, 2.2.3. M-le scripts and func-
tions, 2.
3. Example: The trajectory of a projectile 4
1. Aims and objectives
This session aims to provide you with a recap of the material covered in the Matlab
rst-year course, and introduce you to new aspects of Matlab. While the rst-year course
concentrated on data analysis, here the emphasis is more on computational mathematics
and modelling.
By the end of this session, you should feel condent about using Matlab for calculations
and plots, and be able to produce simple but well-constructed scripts.
2. A review of Matlab
We will start with a brief reminder of Matlab basics before moving on to new material.
Calculate the following expression:
W = Qexp
[A
1
+ Dsin(2d)]
2
,
where Q = 3.8, A
1
= 3 10
12
, D = 1000 and d = 0.1.
Task 1 Matlab as a calculator
2.1 Simple matrix operations
Remember that the operator represents a matrix multiplication. The . operator followed
by the operator represents element wise multiplication.
A review of Matlab 2
a) Input the vector a = [1 1 3] and the matrix b = [3 4 5 ; 2 5 8; 1 3 6].
b) Find the product a b of these two matrices. Can you nd the product b a?
c) Create a 4 10 matrix with elements ranging from 1 to 10 in the rst row, all 10s in
the last column and ones in all other elements.
Hint: try typing doc matrix for information on how to create matrices.
Hint: Try creating an array for each row of the matrix and then combine them.
Task 2 Matrix basics
2.2 Visualizing data
Matlabs inbuilt documentation is useful whenever you need to know how to use a
functionyou can just type help <function> into the command window for an in-
stant summary of the command. If you need more detail, doc <function> will open
up the complete documentation in a new window. For example, typing help plot
into the command window brings up the information plot Linear plot. plot(X,Y) plots
vector Y versus vector X [cont.] followed by more detailed information on the various
command options. Now we can use this information to nd out how to produce plots.
Plot the function f = ge
0.37x
from x = 1 to 100 in steps of 0.5, using a linear and
semi-logarithmic plot where g = 0.01. Label the x and y axes. Also give the graph a
title that contains the function. You may want to look at the help information for the
command semilogy.
Task 3 A simple graph
Matlab can also produce more complicated plots, such as three-dimensional surface plots.
The Matlab command meshgrid() sets up a mesh of gridpoints on which to evaluate the
plot function, and the command surf() plots a three-dimensional surface.
Use Matlab to generate a grid of x and y values to plot the function cos(x)e
0.6y
for
x = 3 to 3 and y = 1 to 1. Plot this function using the matlab function surf().
Task 4 A 3-d graph
2.3 M-le scripts and functions
Remember that MATLAB programs are stored as text in les having names that end
with the extension .m. These les are often called m-les or scripts.
An example of an m-le to produce a plot is given below. Note that it is just a series of
Matlab commands that are carried out sequentially.
A review of Matlab 3
%% A sample matlab script
% This script adds two functions together and then plots them.
% It also demonstrates good script structure and practice.
%% Initialize
% First close all plot windows and clear all variables.
% It is a good idea to always do this, but dont use
% "clear all" if you are working with imported data!
close all
clear all
%% Calculate the function
% We will calculate for 100 points between 0 and 2 pi, inclusive,
% that is, there will be 99 intervals each of (2 pi/99).
N = 2*pi;
npoints = 100;
x = [0:N/(npoints-1):N]; % this creates the vector of x-values
% Now we calculate the function
% Here we will just calculate cos(x)
fn1 = cos(x);
%% Plot the function
% We will plot the function using a red line (r-)
plot(x,fn1, r-)
% Label the axes
xlabel(x)
ylabel(f(x))
Matlab code 1
Copy and paste the sample m-le above into the Matlab editor window.
Make sure you understand what each line doesin particular note the structure of the
comments. Matlab treats each %% as the beginning of each section of code.
Use the Matlab Publish tab (next to the editor tab) and experiment with publishing
the script. Note that:
1. Matlab prints the output of each section of script before moving on to the next
section.
2. Matlab formats the comments directly under the section comments as paragraph
text. This is extremely useful for annotating and documenting your code.
Task 5 Script structure and publishing scripts
Example: The trajectory of a projectile 4
x
y
v
R
H
g
0
Figure 1: The trajectory of a projectile without air resistance. The projectile is launched with ve-
locity v at an angle to the horizontal. On level ground, and with gravitational acceleration g, the
projectile will travel in a parabolic trajectory with a maximum height H and total range R.
3. Example: The trajectory of a projectile
We will now put this to use by looking at a particular physics example that should be
familiar from rst-year mechanicsthe trajectory of a projectile. On level ground, with
no air resistance, a projectile will take the path of a parabola, as in Fig. 1. The trajectory
is dependent only on the initial velocity v
0
(which can be broken down into its x and
y components using the angle of launch ), and can be described using the following
equations:
x(t) = v
0
cos()t, (1)
y(t) = v
0
sin()t
1
2
gt
2
, (2)
R =
v
2
0
g
sin(2), (3)
H =
(v
0
sin())
2
2g
, (4)
T =
2v
0
g
sin(), (5)
where x(t) and y(t) are the position of the projectile at time t after launch, and R, H, and
T give the total range, maximum height, and time of ight of the projectile respectively.
Example: The trajectory of a projectile 5
Write a new m-le script to calculate and plot the trajectory of a projectile. Assume
that there is no friction. Your script should:
1. Ask the user to input the initial velocity and initial angle
2. Calculate the range, time of ight and maximum height of the projectile
3. Calculate the x and y-positions of the projectile for 100 time intervals
4. Write the time, x and y positions to a text (ascii) le
5. Make an animated plot of the trajectory, i.e. a plot which updates itself for
each time interval, and write the values of the time interval, range, time of ight
and maximum height on the plot.
6. Finally, read in the data le you wrote above, and output it to the console.
Use the general structure of the sample script above. Publish the script in .pdf
formatyou will nd that you have to make some changes to your script to do this.
Comment out the lines that cause problems and replace them with lines that work
in this case, and comment on this problem and your solution to it.
You will probably nd the following Matlab commands useful
fprintf(), fopen(), fclose(), fscanf()
sprintf()
annotation()
hold
pause
drawnow
Use the help and/or doc functions to nd out how to use them.
In particular, this blog has a post on the fprintf command that you may nd
useful: http://matlabgeeks.com/tips-tutorials/saving-data-to-les-matlab-fprintf-
command/.
Submitting your work:
Once you are happy that your code contains all the results and annotations,
submit the .m script le via the upload page on Moodle, then see a demonstrator
for marking in-session.
Assessed Task: A script to calculate projectile motion
Documentation link:
http://www.mathworks.com/academia/student center/tutorials/creating scripts.html