Вы находитесь на странице: 1из 14

Version 2014A EG168 Problem Solving in Matlab 03/05/2017

EG168

P R O B L E M S O LV I N G I N M AT L A B

CONTENTS

Getting started...................................................................................................... 2
Logging on.......................................................................................................... 3
Starting Matlab................................................................................................... 4
Help.................................................................................................................... 4
Recommended Text............................................................................................ 5
Assessment........................................................................................................ 5
1. Basic calculations and commands...................................................................6
1.1 Mathematical Operations..........................................................................6
1.2 Variables and Functions............................................................................ 7
1.3 Vectors...................................................................................................... 8
1.3.1 Using Vector Indices............................................................................9
1.3.2 Operations on Vectors.........................................................................9
1.4 Matrices.................................................................................................. 11
1.4.1 Using Matrix Indices..........................................................................11
1.5 Troubleshooting and debugging..............................................................12
Version 2014A EG168 Problem Solving in Matlab 03/05/2017

GETTING STARTED

This is not a textbook, it is a workbook is designed to get you to use Matlab


effectively.

Matlab is a high level scripting language. The best way to learn any programming
language is to try it for yourself

. Each example builds on the previous one, therefore it is ESSENTIAL that you
understand each example and exercise in sequence. There are examples and
exercises throughout the workbook which should be completed in order and
WEEKLY TESTS ON BLACKBOARD for the first FOUR WEEKS.

Matlab is an incredibly useful tool, used widely in industry and academia. It can
perform the simplest calculations, process and plot large quantities of data
quickly or even be used to run complex control programs for large infrastructure
such as power stations. Matlab is great for for applications where large datasets
need repetitive calculations to be carried out.

Advantages of Matlab:

The GUI (graphical user interface) is simple to use.


There are user-friendly in-built functions making it much quicker to work
with than many lower level programming languages such as Fortran, C
etc.
Data is stored in vectors or matrices (blocks of numbers) making
processing and plotting of data quick and simple.

Disadvantages of Matlab: Can use a lot of computer memory

LOGGING ON

Log on using the following:

Username eg<student_no> i.e. eg123456

The first time you log in, your password is your student number followed by
your date of birth.

Password <student_no>/dd/mm/yyyy i.e. 123456/04/07/1993


Version 2014A EG168 Problem Solving in Matlab 03/05/2017

STARTING MATLAB

Open Matlab. You will see the GUI (graphical user interface) as below:

Current Folder location


Command Window Workspace

Current folder contents Command History

The Command Window is where instructions are typed.

The Command History shows previous commands


The Current folder location is the active folder and also displayed are
the Current folder contents.
The Workspace shows what variables are currently stored within Matlab

Check where your current folder location is.

Change this to the H:\ drive where you can save your data.

Save your workspace FREQUENTLY!

HELP

You will not find all the answers in this workbook, be prepared to do your own
research to solve problems. If you get stuck, try the following:

Matlab help type helpbrowser to open a Help window


Online Matlab help forum http://www.mathworks.co.uk/help/matlab/
Post a question on the EG-168 blackboard discussion board for Dr Xavier
or other
students to answer
Version 2014A EG168 Problem Solving in Matlab 03/05/2017

RECOMMENDED TEXT

Attaway (2013) Matlab: A Practical Introduction to Programming and Problem


Solving 3rd Ed. ISBN: 978-0-12-405876-7

1st and 2nd editions also suitable

Available and print and e-book:


https://ifind.swan.ac.uk/discover/Record/635711#.U-SccGORbT4 (log into to
idiscover to find)

ASSESSMENT

Weekly tests on Blackboard (4 x 5% each).

A short group report submission via Turnitin on the Bloodhound supersonic car
(40%). The report will show the presentation of data processed using Matlab.
Version 2014A EG168 Problem Solving in Matlab 03/05/2017

1. BASIC CALCULATIONS AND COMMANDS

In this chapter, you will learn:

Mathematical operations in Matlab


To define variables
How to create horizontal and vertical vectors and use vector indices
Calculations using vectors
How to create matrices and use matrix indices
Troubleshooting

At the end of the session complete Matlab Test 1 (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.

1.1MATHEMATICAL OPERATIONS

At the simplest level, Matlab can be used as a calculation tool by using text
entered into the command window. The correct operators need to be used and
the BODMAS rule applies.

Operation symbol Example


Brackets ( ) (2+3) = 5
Order ^ 2^3 = 8
Divide / 2/3 = 0.666
Multiplication * 2*3 = 6
Addition + 2+3 = 5
Subtraction - 2-3 = -1
Version 2014A EG168 Problem Solving in Matlab 03/05/2017

Exercise 1.1

Aim: Become familiar with simple Matlab syntax (language).

a) Convert the following equations into the Matlab syntax and enter into the
command window. Press Enter to execute the command.
b) Type or copy & paste the correct Matlab code into the 2 nd column
c) Write the correct answer in the 3rd column (select answers below the
table).

Equation Matlab Result


5 1
8+ 23 +20 8+(5/4)*2^3+20*1/3 24.7
4 3

10 (2+10) 210
2
23 2 +2
+113
17 17
-8.3, 11.3

Matlab also has in-built functions for common mathematical expressions.

Example

Type the following into Matlab

sqrt(9)

round(3.4)

Both give the answer 3.

See the end of the chapter for more examples of inbuilt functions.

1.2VARIABLES AND FUNCTIONS

Assigning variables allows greater flexibility in calculations. Variables are case-


sensitive. They must start with a letter but can contain numbers and they must
contain no spaces e.g. a, Velocity1,Temp_celcius. The assignment format
is:

variablename = expression

Example

Type the following into the Matlab Command Window, pressing Enter after each
line to execute each command separately

a=1

A=2

c=3
Version 2014A EG168 Problem Solving in Matlab 03/05/2017

Type the following into the Matlab Command Window, pressing Enter to execute
the command:

a+A+c You should get the answer 6.

Exercise 1.2

Pre-stored variables

There are several variables and matrices pre-stored in Matlab. Type the following
into Matlab and write the value in the right hand column

Variable Value
pi
i
j
eps
realmin
realmax
inf

IMPORTANT NOTE: Take care not to overwrite these variables!

NOTE: ; is used to suppress output in the Command Window. Try typing


b=2+3+4; ending the line with a semi-colon ;. You will see that the command is
processed (b has a value of 9 in the Workspace) but the output is not displayed
in the Command Window.

1.3VECTORS

A vector is a series of variables stored together. Vectors are specified in Matlab in


two ways; rows and columns.

Using a space or a comma to separate values creates a row vector


Using a semi-colon creates a column vector.

This allows more information to be stored. In the table below, data for classic
concept cars is stored:

Table: Stats for Classic Concept Cars

No Car Power (bhp) Speed Time0-60mph (s)


. (mph)
1 Mitsubishi HSR (1987) 295 186 4
2 Aston Martin Bulldog 650 192 4.6
(1980)
3 Bugatti Veron 1183 268 2.4
Supersport (2010)
4 Ferrari Aurea (2003) 500 202 3.9
Version 2014A EG168 Problem Solving in Matlab 03/05/2017

Example

Copy and paste the following into Matlab line by line (press enter after each line):

Vector1 = [1:10]

Vector2 = [2:2:20]

Power_bhp = [295 650 1183 500]

Speed_mph(1) = 186
Speed_mph(2) = 192
Speed_mph(3) = 268
Speed_mph(4) = 202

Time0to60_s = [4;4.6;2.4;3.9]

These are all ways of creating vectors. You will use the Power_bhp, Speed_mph
and Time0to60_s vectors later in the chapter

Note the effect of using the semicolon:

Vector1 = [1:10] creates Vector1 = 1 2 3 4 5 6 7 8 9 10 (from 1 to 10)

Vector2 = [2:4:18] creates Vector = 2 6 10 14 18 (from 2 to 18 in steps of 4)

The last three in the above example vectors from Table 1a. Power_bhp and
Speed_mph are row vectors and Time0to60_s is a column vector. They will now
have appeared in the Workspace.

1.3.1 USING VECTOR INDICES

The position of a number within a vector is known as the index (plural: indices)
or sometimes the element.

Example

For this example you must have completed the examples in the previous section.

Type:

Power_bhp(3)

This returns the value stored in index 3 (position 3) of Power_bhp vector.

Type:

Time0to60_s(1)

This returns the value stored in index 1 (position 1) of the Time0-60_s vector.

1.3.2 OPERATIONS ON VECTORS

Operations can also be performed on vectors:


Version 2014A EG168 Problem Solving in Matlab 03/05/2017

Operation Symbol
Sum of vector sum( )
contents
Size of vector size( )
Average (mean) mean( )
of vector
contents
Maximum value max( )
Minimum value min( )

Example

Use sum( ) to find the combined power of all four cars

sum(Power_bhp)

Operations can be performed on vectors in the same way as single variables.

Example

Try copy and pasting the following into Matlab:

Data1=[1 2 3 4]

Data2=2+Data1

The result is Data2=[3 4 5 6]

Exercise 1.3

Below Table 1 is repeated. Add the values for the sum and mean for the
Power_bhp, Speed_mph and Time0to60_s columns

Convert the Power_bhp and Speed_mph vectors from Imperial to Metric units.
Create two new vectors, Power_kW and Speed_kmh using the calculations above
and fill in the last two columns of Table 1b.

Formula for converting bhp to kilowatts (kW):

Power_kW = Power_bhp x 0.7457

Formula for converting mph to km/h:

Speed_kmh = Speed_mph x 1.609

You can check your answers by using the same data in a calculator or in Excel.

Table 1b: Concept Car stats in Imperial and Metric

No. Car Powe Spee Time0 Power (kW) Speed (km/h)


r d -
(bhp) (mph 60mp
) h (s)
1 Mitsubishi 295 186 4
HSR (1987)
2 Aston 650 192 4.6
Version 2014A EG168 Problem Solving in Matlab 03/05/2017

Martin
Bulldog
(1980)
3 Bugatti 1183 268 2.4
Veron
Supersport
(2010)
4 Ferrari 500 202 3.9
Aurea
(2003)
Sum
Mea
n

1.4MATRICES

A vector is a 1-dimensional line of information, a matrix is a 2-dimensional (or


higher) set of information.

Example

To create a matrix in matlab, use either of the following methods:

Matrix1=[1 3 5 7 9 ; 2 4 6 8 10 ; 11 12 13 14 15]

Matrix2=[1,3,5,7,9 ; 2,4,6,8,10 ; 11,12,13,14,15]

The commands above produce identical 3 x 5 matrices. Notice that once again,
spaces or commas create rows and semi-colons create columns.

1.4.1 USING MATRIX INDICES

As with vectors, matrix indices give the position of a number within the matrix,
but now a row and a column index must be given. The row index is always given
first.

Example

Typing Matrix1(1,3) will return the item in the 1st row and 3rd column = 5

Typing Matrix1(3,5) will return the item in the 3rd row and 5th column = 15

Exercise 1.4
Results
a Matrix1(:,3)
d Matrix1(1:2,3:5)
f Sum(Matrix1(2,:))
g Mean(Matrix1(3,1:2))
h Matrix1(2:3,2:end)
Version 2014A EG168 Problem Solving in Matlab 03/05/2017

Try typing the commands in the left column of the table above into the Command
Window. Match with the results on the right side. Compare the original Matrix1
with the results from the index combinations. What is the effect of using the
semicolon? What is the effect of using end?

Exercise 1.5

Matrices can be used to store different types of linked data. Create a matrix with
the original data about the Concept Cars:

Car Powe Spee Time0


r d -
(bhp) (mph 60mp
) h (s)
Mitsubishi 295 186 4
HSR (1987)
Aston 650 192 4.6
Martin
Bulldog
(1980)
Bugatti 1183 268 2.4
Veron
Supersport
(2010)
Ferrari 500 202 3.9
Copy & Paste Aurea the following into the
Command (2003) Window:

ConceptCarMatrix=[295,186,4;650,192,4.6;1183,268,2.4;500,202,3.9]

Check the values are correct by comparing with the table above. This is now
stored as a 4 x 3 matrix (4 row by 3 column). Check by typing:

size(ConceptCarMatrix)

Each row is a different car, each column is a different data type. Following the
same logic as the previous exercise, what are the commands to extract the
following information from ConceptCarMatrix?

Data required Command


All the data for the Ferrari Aurea e.g. ConceptCarMatrix(4, : )
All the data for the Ferrari Aurea
and Veron Supersport
Speed for all cars
0-60 time for the HSR, Bulldog
and Veron Supersport
Version 2014A EG168 Problem Solving in Matlab 03/05/2017

You can check your answers by comparing with the original data table.

1.5TROUBLESHOOTING AND DEBUGGING

Comon pitfalls:

Are you using the correct working folder?


Capitalisation Matlab variables are case sensitive, e.g. Matrix1(2) is
not the same as matrix1(2)
Rows and Vectors behave differently
Using the incorrect indices within a Matrix

Matlab has a very helpful error check tool. Red text in the command window
indicates a problem, and this will usually tell you what and where the problem is,
e.g.:
Matlab detects
incorrect
operator *
Red line shows
location of
incorrect
operator

In the above example, Matlab has detected an incorrect use of a mathematical


operator.

I define
MatrixA with 6
values This instruction
asks for the 7th
value (it doesnt

In the problem above, MatrixA has six values. When it is interrogated for the
seventh index value, it returns the error message Index exceeds matrix
dimensions.

Blackboard Test 1

5% of EG-168 module mark


Version 2014A EG168 Problem Solving in Matlab 03/05/2017

Now take Blackboard Test 1 (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.

You have Matlab open. You will need to have Matlab open before taking
the test. Once you open the test, the 20 minutes begins.
Version 2014A EG168 Problem Solving in Matlab 03/05/2017

Summary Table 1

Operation Format Example


Brackets () (4+5)*2
Power ^ 5^6
Divide / 2/3
Multiply * 2*27
Addition + 1+1
Subtraction - 1-1
Square Root sqrt( ) sqrt(81)
Sine of argument in i: sin( ), ii: sind( ) i:sin(pi/2), ii:sind(90)
i:degrees ii:radians
Cosine of argument in i: cos( ), ii: cosd( ) i:cos(pi/2), ii:cosd(90)
i:degrees ii:radians
Tangent of i: tan( ), ii: tand( ) i:tan(pi/2), ii:tand(90)
argument in
i:degrees ii:radians
Round round( ) round(9.3)
Size size [row column] = size( )
Sum sum( ) sum(Matrix1)
Average (mean) mean( ) mean(Matrix1)
Maximum Value max( ) max(Matrix1)
Minimum Value min( ) min(Matrix1)
Create a matrix of zeros(x,y) zeros(3,5)
zeros
Create a matrix of randn(x,y) randn(3,5)
random numbers
Create a magic magic(x) magic(9)
square
Create a row vector A=[a, b, c] A=[1, 2, 3]
Create a row vector A=[a b c] A=[1 2 3]
Create a row vector A(1)=a, A(2)=b, A(3)=c A(1)=1, A(2)=2, A(3)=3
Create a row vector A=[a:b:c] A=[1:2:9] gives A = [1 3
5 7 9]
Create a column B=[a;b;c] B=[1;2;3]
vector
Supress output in A+b; a+B;
command window

Вам также может понравиться