You are on page 1of 16

2.

USING M-FILES AND PLOTTING WITHIN MATLAB

In this chapter you will build on the knowledge developed in Chapter 1 and:

Learn about and annotate .m files


Input and output
Writing algorithms
Vector algebra
Learn to plot data
Troubleshooting and debugging

In Section 1, the commands were entered directly into the Command Window. If
you want to create several sequential commands, .m file scripts are more
useful.

At the end of the session complete Matlab Test 2 (5% of module mark). You will
need to have completed all the examples and exercises in order to complete the
Test.

Allow 20 minutes to complete the Matlab Test.

2.1 MATLAB .M FILE SCRIPTS

2.1.1 CREATING AND RUNNING A SINGLE .M FILE

To create an .m file, click on New> M-file. This opens a text window. Save this .m
file with the name HelloWorld.m.

These .m files will appear in the Current Folder Contents window. If you close
the windows, you can reopen them by double clicking on the .m file icon.

Example

Open a new .m file called HelloWorld.m and type:

disp(Hello World)

Save it. (Important note: .m files do not automatically save. Look for the
little star on the .m file icon this indicates it is not saved. Always
save .m files before trying to execute them)

Run the HelloWorld.m file by either:

-Typing Hello World in the command window, or

-Dragging and dropping the HelloWorld.m file from the Current Folder window

These actions will cause the operations in the .m file to be executed and Hello
World to be displayed in the command window.
Exercise 2.1

Now create an .m file with the data from the last chapter called ConceptCars.m.
Type the following into the .m file window:

%Concept Car Comparisons

Power_bhp = [295 650 1183 500];

Speed_mph = [186,192,268,202];

Time0to60_s = [4;4.6;2.4;3.9];

Power_kW = ???

Speed_kmh = ???

Refer to Chapter 1 for the calculations for metric power and speed vectors.

Save and close the ConceptCars.m file. (Important note: .m files do not
automatically save. Look for the little star on the .m file icon this
indicates it is not saved. Always save .m files before trying to execute
them)

Run the ConceptCars.m file by either:

i) Typing ConceptCars in the command window, or


ii) Dragging and dropping the ConceptCar.m file from the Current Folder
window

These actions will cause the operations in the .m file to be executed.

2.1.2 DEVELOPING ALGORITHMS, ANNOTATIONS, INPUTS AND OUTPUTS

When writing any computer program, it is a good idea to write down the steps
that the program will complete. This sequence of steps is called an
algorithm. When presented with a problem to solve, use the GOAL
methodology to develop the algorithm then the program. This approach
works with both simple and complex programs.

G Gather information. What do you want to do? What information do you


already have? What calculations do you need to perform?

O Organise. Work out what steps are needed and write the stages in an
algorithm and in Matlab

A Analyse. Run the program.

L Learn. Does it work? Can it be improved?

Example

Problem: To write a program to find the power in a circuit if the current and
voltage are known.
G Gather Information Equation: P=IV
Power in Watts unknown
Current in Amps known
Voltage in Volts known
O Organise Problem algorithm
Step 1: Get values for current and voltage
Step 2: Use equation P = IV to calculate Power
Step 3: Output Power
A Analyse Run the program
L Learn Does it work? Can it be improved?

Open a new .m file. Call it CalcPower.m and copy & paste the following:

%CalcPower.m
%Program to calculate Power

%Step 1 Get values for current and voltage


Current = input('Enter value of current in amps: ')
Voltage = input('Enter value of voltage in volts: ')

%Step 2 - Use equation P = IV to calculate Power


Power = Current*Voltage

%Step 3: Output Power


disp(Power)

Save the file and run it. This script will now prompt you for values of current and
voltage, then calculate the power.

Three new structures are introduced here.

Getting input: Expression = input(Text requesting input)

Displaying Output: disp(Expression)

% is for comments. Matlab ignores anything to the right. This allows annotations to be made
instructions and explanations of what is happening in the script. Get in the habit of annotating all
scripts and programs so that you and other people can interpret your work easily.

Exercise 2.2

Create a new .m file script called LatentHeat.m to calculate energy required to


melt solids.

Inputs are mass and latent heat of materials (columns 2 and 3 the table below)

Output is the heat in Joules required to melt different solids. Annotate your
script appropriately.

Use the equation for heat capacity:

Heat (J) = mass (kg) x latent heat capacity (J/kg)

Material Mass Latent Heat Heat required to


J/kg melt (J)
Ice 1kg 334,000 334 kJ
Aluminiu 200g 24,500
m
Hydroge 500g 58,600
n
Watch units!
Follow the format in the previous example.
Use a calculator to check your answers.

%Script to calculate Heat Capacity


%Prompt user for the mass
Mass=????('Enter the mass in kilograms: ')

%Prompt user for latent heat


LatentHeatValue=????('Enter the value for Latent Heat: ')

%Calculate the Heat Energy required for fusion to occur


HeatEnergy=?????;

%Display heat energy


disp(HeatEnergy)

Exercise 2.3

Create a new .m file script called Conduction.m.

Write it so that it will calculate the rate of flow of heat from through a strut of
area 0.001m2, length 20 cm and thermal conductivity 237 Wm -1C-1 within the
Bloodhound SSC.

Inputs are temperature at either end of the strut TH and TC.

Output is rate of heat loss Q/t in J/s

Q T TC
kA H
t L

Where Q is heat in Joules (J), t is time in seconds (s), k is thermal conductivity (Wm-1C-1),
TH is the hot end of the strut, TC is the cool end and L is the length.

Try the following temperature differentials:

TH TC Q/t
20 15 5.925 J/s
200 15
500 20
Copy and paste into Conduction.m and fill in the blanks for the script below:

%%Program to calculate Heat transfer

%Step 1 Get values for current and voltage


TH =?????('Enter the temperature at the hot end: ')
TC = ?????('Enter the temperature at the cool end: ')

%Step 2 - Use equation to calculate heat transfer


RateOfHeatLoss = ????

%Step 3: Output Power


disp(RateOfHeatLoss)

2.2 MATRIX ALGEBRA

First recall the definitions:

A scalar is a single value (a matrix with 1 row and 1 column)

A vector is a list of numbers (a matrix formed from either 1 row or 1 column)

A matrix is any grid of numbers (often with multiple rows and or columns), BUT
note that the term matrix can also be used to refer to vectors and scalars.

2.2.1 ADDITION AND SUBTRACTION OF MATRICES

A scalar (a single number) can be added to any matrix. Matrices can be added
together only if they share the same dimensions.

Example - Adding a scalar quantity.

Create a new .m file called Vessels.m. The masses of 6 empty vessels are listed
in a 2 x 3 matrix:

%Define the masses of empty vessels

MassV_g=[23 34 20 ; 42 16 19]

A fluid amount of mass 10g is added to each vessel:

%Adding 10g fluid to each vessel

MassVF_g=MassV_g+10

MassVF_g will give the new mass of each vessel plus the mass of the fluid added
when the .m file is run.

To add and subtract matrices, they must have the same number of rows and
columns.

Example Adding (subtracting) matrices together.


The masses of the 6 partially filled vessels are repeated here. A second matrix
has the amount of fluid that is to be either added or taken away from the
vessels. Copy and paste the following two 2 x 3 matrices into Matlab:

%Define fluid mass to be added or subtracted from vessels:

MassF_g=[2 4 5;2 2 1];

Try adding and subtracting the masses MassV_g and MassF_g:

%Adding masses

MassVF1_g= MassVF_g + MassF_g

To subtract the masses:

%Subtracting masses

MassVF1_g= MassVF_g - MassF_g

Run the Vessels.m file. Since they are both 2 x 3 matrices, they can be added or
subtracted.

Note: Try adding MassA=[1 2 3; 4 5 6] and MassB=[ 5 6; 3 5].

You will see that the dimensions do not agree so they cannot be added.

2.2.2 MULTIPLICATION OF SCALARS VECTORS

Multiplication can be either by a scalar or vectors can be multiplied together.

Example Multiplying by a scalar quantity

The six partially filled vessels from the previous chapter are placed on a flat
surface. Calculate the force exerted on the surface by the vessels.

To convert from a mass to a force we need to multiply by gravitational


acceleration:

%Calculate force exerted by vessels

ForceVF_N = MassVF_g*9.807

ForceVF_N will give the force of each vessel in Newtons.

To multiply vectors together, the row vector must be the same length as the
column vector:

Exercise 2.4 Multiplying vectors together

In the Matlab Command Window, copy and paste in the following two lines:

MatrixA=[ 10 12 14 9]

MatrixB=[3 ; -3 ; 4 ; -4]

Try copying and pasting the following into the Command Window one at a time:
MatrixA*MatrixB

MatrixB*MatrixA

MatrixA*MatrixA

MatrixB*MatrixB

One of the above produces a scalar (single number), one produces a 4 x 4 matrix
and two are invalid. Which one?

2.2.3 TRANSPOSING

To multiply two row vectors of the same size, we can transpose using .

Example Transposing

Copy and Paste the following two matrices into Matlab:

MatrixP = [ 5 2 7 5 9]

MatrixQ = [ 9 6 4 2 2]

Try multiplying them together:

MatrixPQ = MatrixP * MatrixQ

It doesnt work! There is an error message saying:

Error using *

Inner matrix dimensions must agree

Try :

MatrixPQ = MatrixP + MatrixQ

Including the transposes the second matrix, allowing the two matrices to be
multiplied.

2.3 SIMPLE PLOTS

Matlab has a range of plot functions:


Example

Create a new .m file called LandSpeedRecord.m. Create two row vectors Year
and SpeedRecord_mph:

%Create data vectors


Year = [1898, 1906, 1920, 1928, 1933, 1938, 1947, 1963, 1964, 1965,
1970, 1983, 1997];
SpeedRecord_mph = [39, 128 155 208 272 358 394 407 537 601 622 633
763];

Now create graphs of the data, copy and paste the following:
%Plot 1:Bar Graph
figure
bar(Year,SpeedRecord_mph);
%Plot 2:Line Graph
figure
plot(Year,SpeedRecord_mph);
%Plot 3: Scatter graph
figure
scatter(Year,SpeedRecord_mph)
%Plot 4: Stem graph
figure
stem(Year,SpeedRecord_mph)

This will produce the graphs shown below:


800

800
700

700
600
600
500
500
400
400

300
300

200
200

100
100

0 0
1898 1906 1920 1928
1933
1938 1947 1963
1964
1965
1970 1983 1997 1880 1900 1920 1940 1960 1980 2000

800
800

700
700

600
600

500
500

400
400

300
300

200 200

100 100

0 0
1880 1900 1920 1940 1960 1980 2000 1880 1900 1920 1940 1960 1980 2000

Create labels for the x-axis and y-axis for each graph using the following:

%Create x-axis label


xlabel(Year)
%Create y-axis label
ylabel(Maximum Speed (mph))

Now create a title for each graph using the following:


%Create a title
title(Land Speed Record by Year)

The figure command creates a new blank plot. If you attempt to plot multiple
figures without using this figure command, each new plot will overwrite the last.

2.3.1 TITLES AND LABELS

When creating labels and titles, the following syntax is used:

xlabel(str)
ylabel(str)
title(str)
Where str is a string, Matlabs reads a string as a word not a number. More on
data types in the next weeks chapter.

Add gridlines by typing

grid on
2.3.2 CUSTOMISING PLOTS: COLOUR, LINE AND MARKER TYPES

Matlab gives a wide range of control for plot appearance. Various linetypes, plot
symbols and colours can be obtained with the format:

Plot(x,y,s)

Where s is a character string made from one element from any or all of the
following three columns:

For example, plot(x,y,c+:) plots a cyan dotted line with plus markers

Example

In LandSpeedRecord.m, modify Plot 2 to a red dashed line and Plot 3 to green


stars.

%Plot 2:Line Graph


figure
plot(Year,SpeedRecord_mph,r)
%Plot 3: Scatter graph
figure
scatter(Year,SpeedRecord_mph,g*)

To plot a partial dataset, use the index (position) to select the appropriate data.

Example

To plot only the dataset between 1963 (index 8) and 1997 (index 13 in a red
dotted line) add a new plot:
% Plot 5: Scatter graph 1963-1997 inclusive
figure
plot(Year(8:13),SpeedRecord_mph(8:13),r:)

2.3.3 USEFUL PLOT RELATED FUNCTIONS


clf clears the current figure window

figure creates a new, empty figure window

hold freezes the current plot, allowing multiple plots to be


superimposed on each other

legend displays strings associated with the data

grid on/off toggles gridlines on and off

close all deletes all the figure windows on the desktop

Exercise 2.5

a) Both Year and SpeedRecord_mph vectors are 13 datapoints long. Using


index 14, add the projected date of 2015 and speed of 1000 mph to the
vectors Year,SpeedRecord_mph in LandSpeedRecord.m

b) Create a new plot Plot 6 in LandSpeedRecord.m called:

%Plot 6: Projected Land Speed Record

to include the projected run of the Bloodhound Supersonic Car in 2015 at


1000 mph.

Recreate this graph:

Projected Land Speed Record


1000

900

800

700
Maximum Speed (mph)

600

500

400

300

200

100

0
1880 1900 1920 1940 1960 1980 2000 2020
Year

You need to differentiate between actual and projected speed records:

use magenta stars to denote datapoints


use a magenta solid linetype for the records from 1898 to 1997
use a magenta dotted linetype to show the projected record from 1997 to
2015
add gridlines
Add axis labels and a title
Add a vertical green line for 2014 (this year)

%Plot 6: Projected Land Speed Record


figure
plot(??????????,???????????????,'m-*')
hold ??
plot(??????????,???????????????'m:*')
plot(????,???????????????,'g-')
%Create x-axis label
???????????
%Create y-axis label
???????????
%Create a title
???????????
grid ??

Save your .m file.


2.4 TROUBLESHOOTING AND DEBUGGING

When errors occur in .m files, Matlab usually tells you exactly where and what
has occurred. See the following:

My M3.m file defines variables


a and b then tries to perform
calculation A+b

Matlab tells you it doesnt


recognise A

Matlab tells you the problem is on


the 3rd line of M3.m

When red text appears use it to find where you have gone wrong. In this
example, there is an undefined variable. It is because Matlab is case sensitive
and the variables a and A are not equivalent.
)

Blackboard Test 2

5% of EG-168 module mark

Now take Blackboard Test 2 (find it in Matlab/ Assessments). This is a 20 minute


timed test, you can have a maximum of two attempts. Before starting the test
you must:

Ensure you have completed all the examples and exercises in the chapter,
including completing the following .m files:

Hello World.m
ConceptCars.m
LatentHeat.m
Conduction.m
LandSpeedRecord.m

You will need to have Matlab open before taking the test. Once you open
the test, the 20 minutes begins.
Summary Table 2

Operation Format Example


Create a new .m file New> M-file
Display value of a disp( ) disp(a)
variable
Display string (text) disp( ) disp(Hello)
Comments % % This program is good
User Input Expression = input(Text num=input(What is the
requesting input) number?)
Create a new figure figure figure
Bar graph bar(x,y) bar(x,y)
Scatter graph scatter(x,y) scatter(x,y)
Line graph plot(x,y) plot(x,y)
Stem graph stem(x,y) stem(x,y)
x-axis label xlabel( ) xlabel(Variable x)
y-axis label ylabel( ) ylabel(Variable y)
Graph title title( ) title(Land Speed
Record)
Grid grid on/ grid off grid on/ grid off
Hold/ Freeze current hold hold
graph
Legend legend legend
Clear current figure clf clf
window
Delete figure windows close all close all
Format graphs plot(x,y,s) plot(x,y,g+:)

You might also like