Professional Documents
Culture Documents
In this chapter you will build on the knowledge developed in Chapter 1 and:
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.
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
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)
-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:
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)
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.
O Organise. Work out what steps are needed and write the stages in an
algorithm and in Matlab
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
Save the file and run it. This script will now prompt you for values of current and
voltage, then calculate the power.
% 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
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.
Exercise 2.3
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.
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.
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:
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.
A scalar (a single number) can be added to any matrix. Matrices can be added
together only if they share the same dimensions.
Create a new .m file called Vessels.m. The masses of 6 empty vessels are listed
in a 2 x 3 matrix:
MassV_g=[23 34 20 ; 42 16 19]
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.
%Adding masses
%Subtracting masses
Run the Vessels.m file. Since they are both 2 x 3 matrices, they can be added or
subtracted.
You will see that the dimensions do not agree so they cannot be added.
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.
ForceVF_N = MassVF_g*9.807
To multiply vectors together, the row vector must be the same length as the
column vector:
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
MatrixP = [ 5 2 7 5 9]
MatrixQ = [ 9 6 4 2 2]
Error using *
Try :
Including the transposes the second matrix, allowing the two matrices to be
multiplied.
Create a new .m file called LandSpeedRecord.m. Create two row vectors Year
and SpeedRecord_mph:
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)
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:
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.
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.
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
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:)
Exercise 2.5
900
800
700
Maximum Speed (mph)
600
500
400
300
200
100
0
1880 1900 1920 1940 1960 1980 2000 2020
Year
When errors occur in .m files, Matlab usually tells you exactly where and what
has occurred. See the following:
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
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