You are on page 1of 23

Introduction to Programming in MATLAB

Unit EE10086 Given by: D. M. Monro (MATLAB) M. J. Balchin (SIMULINK) P. J. Leonard (Lab)

Aims & Objectives

To understand the use of computers for: Solving Problems Making Calculations Manipulating Data Presenting Results

Structure of This Unit


l

Structure of Lectures
l1 l2

20 - ish Lectures

- 16 on MATLAB (DMM) - 3 on Simulink (MJB) - 1 to introduce Lab (PJL)


As required

l l l

Laboratory
2 Groups AB and CD

l l

Tutorials 2 Hour Examination (January)


l

3 hours Laboratory each week. 2 Lab Assessments


l l

Weighting 50% of Unit

Unequal weighting Total 50% of Unit

Introduction - this lecture Calculations ~ 3 lectures l 3 SIMULINK ~ 3 Lectures At End l 4 Programming ~ 5 Lectures l 5 Arrays and Plots ~ 4 lectures l 6 Matrices & Graphics ~ 4 lectures l Plus 1 to introduce Labs

Note heavy weighting of Lab


l Its

hard work and its important!

Recommended Texts
l l

Using MATLAB
l Turn l Double l You

You need a quick reference to supplement online help So it is suggested that you buy (XX is the Version)
l

your computer on click the MATLAB icon:


MATLAB 6.1.lnk

Getting Started with MATLAB XX: A quick introduction for scientists and engineers, by R Pratrap, Oxford University Press, ISBN 0-19-512947

will get a prompt:

More substantial references are


Mastering Matlab XX, by D Hanselman & B Littlefield, Prentice Hall l Matlab XX for Engineers, by A Biran & M Breiner, Addison Wesley l Introduction to MATLAB XX for Engineers, by Palm, McGraw Hill
l

>>
l The

dialog is always: prompt command response >> You type this Matlab reacts l When you are finished, type exit or quit

Software and Computing I

Page 1

Getting Help
l Refer

Simple Examples
l

to the text l Use online help l As soon as you get a chance try out:
help why where
l If
l in

As a calculator: 1.27*7 ans = 8.8900 3+4/5 ans = 3.8000 22/7;

You can define variables: x = 1.27 x = 1.2700 7*x ans =

help topic what whos the lab please

lookfor keyword who


l

8.8900

all else fails, ask an expert

Something funny here ?

who Your variables are: ans x

Something More Clever


l We l Is

Some Exercises
Find out about the fix function. Using only the rem and fix functions you can do these exercises using MATLAB as a calculator with variables. You do not need to write m-files, but you may. 1.1Is 32763 a prime number? 1.2Find all prime factors of 4410. 1.3 A funny shaped box of chocolates has 7 chocolates on a layer and there are three layers. How many boxes do I need to hold 4410 chocolates? 511 chocolates? 1234567 chocolates? 1.4 On what day of the week were you born? To do 1.4 & 1.5 you need to know the rules for leap years. 1.5 In what years in the 21st century will your birthday be on a Saturday?

are given a decimal integer n it prime?

There is a remainder function: rem(n, b)


l So

we do it:
rem(n, 5) ans = 1 rem(n, 7) ans = 3 Is that necessary? Why?

n=31; rem(n, 2) ans = 1 rem(n, 3) ans = 1

2. Calculations ~ 3 Lectures
l2.1

Building MATLAB Programs l2.2 Arithmetic and MATLAB l2.3 Clean up your output

l2.1

Building MATLAB Programs

l.m

Files lCreate, Edit and Save lComments and Help lSome Special Commands

Software and Computing I

Page 2

.m Files (Script Files)


l l l

Create, Edit and Save


l l l

l l

A .m file or script file is a sequence of MATLAB instructions. Suppose we want to compute nCr = n!/r!(n-r)! = n*(n-1)*(n-2) . . .(n-r+1) / r! 1. Make a file called ncr.m It contains one line of MATLAB: nCr = prod(n-r+1:n) / prod(1:r); To use it, assign values to set n and r, and then enter the name of the script file Its also = n*(n-1)*(n-2) . . .(r+1) /( n-r)!

l l l

Creat a script file by selecting New from the MATLAB file menu This calls up a nice MATLAB editor Edit with keys and mouse: Learn how to place cursor with mouse or keys add and remove characters cut and paste text Save the file as a meaningful name Then MATLAB can use it Remember to save it every time it is changed. (MATLAB 7 forces you.)

Helpful Punctuation Comments and Help


l Use l The l To

the % symbol to begin a comment comment continues to the end of the line l Comments are a vital part of documentation: Write them as you create a program, not later l The command help name displays comments at the beginning of the m-file l The command lookfor keyword searches the first line of every m-file in the path for the keyword, and displays the line if it finds it.

suppress display of a result end each line with a semicolon >> prod(1:10) will display the result >> prod(1:10); will not display the result l To pack multiple commands on one line, separate them by commas or semicolons >> prod(1:5); prod(1:6); prod(1:7); >> prod(1:5), prod(1:6), prod(1:7), l To contnue a line that is too long, use x = 1+ 2 + 3 + 4 + 5 + 6 +7 +8 + 10 + 11 + 12 + 13 + 14 + 15;

Some Special Commands


l To

Some Exercises
2.1.1 Go to computer and in MATLAB try the command help general. This will give you a list of general commands in MATLAB. Many of them are useful to you already. Using help, find out what each of them does, and try them. 2.1.2 Write a script file that will tell you what the chances are that r people from a group of n will have the same birthday. 2.1.3 The bits of an 8 bit positive binary number are rotated right, that is, the old LSB becomes the new MSB, the old MSB is shifted one to the right, and so on. Write a script file to calculate the new value when this is done. Then do rotation left. Finally, try reversing the bits. 2.1.4 The Reverend Zeller, in 1883, came up with a wonderful formula to help you with calendar calculations. The months in a year have unequal numbers of days. If you assume each is 28 days long, then Zellers formula extras = fix ( (13*month-1)/5) - 2 gives you the number of irregular days added on. Months are counted from March, I.e. March=1, April = 2 . . . February = 12. Try it! Now write a script file to work out the day of the week for any date after 1 March 1600 (which was a Wednesday or was it?)

access a command of the computers operating system, use ! command such as !dir l To see what directories are searched by MATLAB, use path l If there is a file called startup.m in the path, it will be executed when you start MATLAB l So for example you can use path in startup.m to inform MATLAB about your directories

Software and Computing I

Page 3

What, No Integers?
l 2.2

Arithmetic and MATLAB


What, no Integers? Display format l Constants & Special Constants l Variables l Special Variables l Arithmetic Operators l Priority
l l

By Default MATLAB Values are Double Precision Complex Matrices Not really, but believe this anyway) Double Precision means 64 bits, or about 14 decimal places. eps is the smallest number: inf is the largest number:

l l

So the largest value is?

Display Format
l Matlab

Constants & Special Constants


l To

shows values to a standard precision normally format short = 4 decimal places l You can change this with the format command: format short 4 d.p. short e long long e bank hex rat

use a constant, just write a number: 1 43 75.76 -12e-34 l There are some special constants that have names: pi inf NaN i, j eps realmax realmin l This is pretty interesting: >> format hex >> eps >> realmax >> realmin

Variables
l Just

as in Maths, these are names that can be given values that can then be manipulated l Variable names start wiith a letter, followed by any number of letters, digits or underscores _ l The Good News: To define a MATLAB variable, just use it in context: >> a = 1 >> a = a+2 >> b = 5 >> c = a+b

Variables
l Good

and Bad News:

l Matlab

is Case sensitive: Nigel and nigel and NiGeL are NOT the same Really Bad News:

l The

l Spelling

mistakes cannot be detected & Spelling mistakes can cause serious errors

Software and Computing I

Page 4

Special Variables Arithmetic Operators


l See

Text or help: ans computer nargin nargout l You can highjack one of these names, but thats just silly >> computer = computer + 1 l You can clear your variables with clear l You can examine your variables with who and whos

l Add

or subtract: A+B A-B l Mutiply or Divide: A*B B*A Funny Division: A\B B\A l Raise to a Power: A^B

-A+B A/B B/A

Priority
l l l

Mathematical Functions
l Trig

3 + 4 * 5 could mean one of two things: (3 + 4) * 5 or 3 + (4 * 5) Similarly, what do these mean: 3+4/5 3+4\5^6 The priority of operations is: high (done first) ^ / or \ or * low (done last) + or You can work out the answer by placing brackets around groups of equal priority: A + B * C * D ^ E is (A + (B * C * (D^E)))

function

sin cos tan cot sec csc - do they work in radians? Can you make them work in degrees? asin acos atan acot asec acsc - what range of angles do they work for? So what is special about atan2? Hyperbolic versions sinh asinh etc.
l Exponential l Complex

functions

exp log log10 sqrt log2

functions

abs angle conj real imag

Integers and Reals


l Look

Some Exercises
2.2.1 Before you try them, what do you expect from these MATLAB expressions: 0 + eps 0 - eps inf + eps inf - eps realmax + eps realmax - eps realmin - eps realmin + eps realmax - realmin realmin realmax realmin + realmin realmax + realmax 0 + eps - eps realmax + eps - eps 2.2.2 Now try all the above expressions in MATLAB, and explain in each case what MATLAB is doing. 2.2.3 First predict by reasoning, and then confirm using MATLAB the results of the following expressions: 4+5/6 4+5\6 4*5\6 5 + 6 * 2 ^ 3^ 4 2.2.4 Are operations of equal priority done right to left or left to right? 2.2.5 There is a formula for the sum of all the numbers from 1 to n. Work it out or look it up. use it to find the sum of all the numbers from 1 to 1000.

at help elfun l Fixing and Rounding:


You have already seen the functions fix(x) round towards zero rem(n,d) remainder of n/d
l Others

you should know about:


round towards nearest integer round towards - inf round towards inf answer -1, 0, or 1

round floor ceil sign

Software and Computing I

Page 5

l2.3

Clean up your output

Input from Keyboard


l The

lExample:

Find a Sine lScreen Output is untidy lExample - print a table lThe Format lInput from Keyboard

input command, with a friendly message:

variable = input (message)


l The

message is displayed on the screen. MATLAB waits for you to enter something, then it is assigned to the variable. l So experiment with this, in particular can you make it fail by entering junk?

Example: Find a Sine


% Program to find a sine % D. M. Monro 6 Oct 1997 d = input(Enter angle in degrees to find sine ) x = d * pi / 180; finesine fprintf(\n Sine of %-6.2f degrees is %-6.2f \n, d, sin(x))

l MATLABs l You

screen output is untidy know that it can be silenced with the ; l Now you will see how to control precisely what it displays l . . . but you wont like it! l The fprintf command does it: fprintf (format, values) You give one format in quotes and one list of values separated by commas The values are displayed using the format specification

Example - Print a Table


% Loantab.m prints an interest table fprintf('\n\n\n\t\t Table of Compound Interest') fprintf('\n\tRate =\t 4%% \t 6%% \t 8%% \t 10%%') fprintf('\n Periods') for p = 1:10 fprintf('\n %-6u',p) for i = 4:2:10 fprintf('\t %-6.2f',(1+i/100)^p) end end
l This

Example
is what it printed:
10% 1.10 1.21 1.33 1.46 1.61 1.77 1.95 2.14 2.36 2.59 Table of Compound Interest Rate = 4% 6% 8% Periods 1 1.04 1.06 1.08 2 1.08 1.12 1.17 3 1.12 1.19 1.26 4 1.17 1.26 1.36 5 1.22 1.34 1.47 6 1.27 1.42 1.59 7 1.32 1.50 1.71 8 1.37 1.59 1.85 9 1.42 1.69 2.00 10 1.48 1.79 2.16

Software and Computing I

Page 6

The Format
l The

The Format - Continued


l The

format is a character string containing: messages in plain text control specifications starting with \ conversion specifications starting with % l This facility is borrowed from the C language l Control specifications include: \n new line \t tab \b back 1 space \r return to beginning of line \\ print \ \ or print %% print % \a irritating noise l More details in any C manual

conversion specification controls the exact layout of data. It takes the form: %- w .d C l The - is optional and causes the field to be left justified The w is optional and specified the width of the field in characters The .d follows a w and is also optional. It specifies the number of decimal places The C specifies the type of conversion

Yet More Format


l Some

Example Cool Tab


% Go to Tab Position on a new line Tab = 23 fprintf('\n') for Cool = 1:Tab % This is a for loop fprintf(' ') end

types of conversion are:

%f Fixed Point, i.e. real with decimal places %e Exponential, i.e. real with an exponent %g Use shortest of %f or %e %u Integer, I.e. no decimal places %X Hexadecimal in CAPITALS %x Hexidecimal in small letters %s Character String
l Examples:

%-f Left adjusted real number %8f Real number exactly 8 characters wide 8.2f Real 8 wide including 2 decimal places

Preview: CoolTab as a function


function CoolTab(Tab) % function CoolTab(Tab) % Go to Tab Position on a new line fprintf('\n') for Cool = 1:Tab fprintf(' ') end

Some Exercises
Officially you do not yet know what a loop is, except that you had a preview of it in the interest table calculation. The following should be done the hard way, I.e. without loops, and then (or later) see how much neater a loop structure makes them: 2.3.1 Write a program to print out 8 rows of Pascals Triangle which is a table of the values of nCr laid out as: 0C0 1C0 1C1 2C0 2C1 2C2 (Note that the ends of the rows have value 1, and the others are the sum of the two above them. You might or might not make use of this fact!) 2.3.2 We will see how MATLAB makes graphs for us soon enough, but here the idea is to make the graph in the command window using only fprintf. Graph one cycle of a sine wave. Graph one cycle of a cosine wave. Graph one cycle of a sine wave and a cosine wave together.

Software and Computing I

Page 7

4. Programming ~ 6 Lectures
4.1 Control of Programs
Flow diagrams l The for loop - iteration l Power series - evaluating sines - recurrence l Solving Ordinary Differential Equations - Eulers method l The while structure l Logical expressions l The if structure l Example - finding roots l More control commands l Exercises
l

The for loop


l

l l

Start a MATLAB loop with for and end it with end: for variable = start : step : finish any series of statements end The statements within the loop are repeated with the variable taking all the values from start to finish, separated by step If no step is given, 1 is used start : step : finish is a special kind of expression that occurs in other places

l 4.2

Functions and Scripts

Example Cool Tab


% Go to Tab Position on a new line Tab = 23 fprintf('\n') for Cool = 1:Tab % This is a for loop fprintf(' ') end

Preview: CoolTab as a function


function CoolTab(Tab) % function CoolTab(Tab) % Go to Tab Posiiton on a new line fprintf('\n') for Cool = 1:Tab fprintf(' ') end

Adding up - iteration
l Iteration

Power Series - iteration again


l

is when a similar calculation is repeated over and over l Example: Add the numbers from 1 to 10 l So heres a program:
summy = 1; %Initialise for t = 1 to 10 summy = summy+t; % add them up end summy

We know sin x = x - x^3 + x^5 - x^7 + . . . 3! 5! 7! So heres a program:


maxterm=21; sine = x; for pow = 3:2:maxterm sine = sine + (-1)^((pow-1)/2) * x^pow / prod(1:pow); end sine

Software and Computing I

Page 8

Recurrence
l

Observe
sin x = term 1 + term 3 + term 5 + . . . and term n = (- term n-2 ) * x^2 n * (n-1) The above is a recurrence formula

The whole program sinerec.m


% Recurrence for sin (x) to x^maxterm % Give it x, answer in sine % D. M. Monro 30 Sept 1997 maxterm=21; sine = x; term =x; for pow = 3:2:maxterm term = -term * x^2 / (pow*(pow-1)); sine = sine + term; end sine

So the program could be


l l l l l l l

maxterm=21; sine = x; term =x; for pow = 3:2:maxterm term = -term * x^2 / (pow*(pow-1)); sine = sine + term; end sine

Why is this efficient? Can it be improved?

Eulers Method Tough Stuff!


l

Example: Pint Inflation


Suppose the cost of a pint of beer is changing constantly by d pint = F(pint) dt Euler said pint(future) = pint(now) + time step * F(pint) So if we know the present value and the rate of change, we can predict the future! Example: Its going up r pence per unit of time Example: Its going up r% per unit of time

l Suppose

dx = dt
l Euler

I have a process described by F(x) This is an Ordinary Differential Equation (ODE)

l l l

proposed that this can be solved by

x(now + t) = x(now) + t * F(x) where t is the time step l If you apply this repeatedly, its a recurrence!

The Program Lubejob1.m


% Lubejob1 solves ODE order 1 by Euler method % D. M. Monro 1 Oct 1997

To Plot it - make an array


% Lubeplt1 solves and displays ODE order 1 by Euler method % D. M. Monro 1 Oct 1997 % Supply as global variables: % steps = number of steps to take % deltat = step size % start = initial value of solution % Supply the file deriv1 to compute the time % derivative of the solution x at time t for step = 2:steps+1 % Notice that t is not actually used in here. % So why bother with it? close all poft=start; parray=poft; t=0; t = t + deltat; derivp1a; poft = poft + deltat*deriv; parray = [parray poft]; end plot(parray) parray

% Supply as global variables: %steps = number of steps to take % deltat = step size %start = initial value of solution % Supply the file deriv1 p = start; t = 0; for step = 2:steps+1 t = t + deltat;
deriv1a; % deriv1a computes the slope p = p + deltat*deriv

end

Software and Computing I

Page 9

It could be more complicated


l Suppose

The Program Lubplt2.m


% Lubeplt2 solves and displays ODE order 2 by Euler method % D. M. Monro 1 Oct 1997 % Supply as global variables: % steps = number of steps to take % Do the Euler prediction % deltat = step size p1oft = p1oft + deltat*dp1; % startp1 = initial value of solution for p1 p2oft = p2oft + deltat*dp2; % startp2 = initial value of solution for p2 % Save in the array % Supply the file derivp2 to compute the time p1array = [p1array p1oft]; % derivative of the solution (p1, p2) at time t p2array = [p2array p2oft]; close all end p1array = startp1; p1oft = startp1; % Display the results p2array = startp2; p2oft = startp2; taxis = [0:deltat:steps*deltat] t = 0; plot(taxis,p1array) for step = 2:steps+1 figure step t = t + deltat; plot(taxis,p2array) derivp2; figure plot(p1array,p2array)

d^2 pint = F(pint) = 100 - pint dt ^2 l To use Eulers prediction, we need the ODE to have only first derivatives. Theres a trick: let p1 = pint and p2 = d p1 / dt then d p2 / dt = d^2 pint = F(pint) = 100 - pint dt ^2 l So lets do it!

Derivative Script derivp2.m


% derivp2 computes time derivatives (dp1, dp2) % for second order ODE solution % D M Monro 1 October 1999 dp1 = p2oft; dp2 = 100-p1oft;
l

Moon Lander Third Order and Nonlinear


A spacecraft of mass 500 Kg approaching a moon has an approach velocity of 100 metres per second when it is at altitude 1000 metres. The acceleration due to gravity on the moon is 1 m/s2. When the rocket is fired it exerts a vertical force of 5000 Newtons to slow the spacecraft. But! The engine consumes 10 Kg of fuel per second, and there is only 50 Kg of fuel. So the mass of the rocket starts to decreases when the rocket is fired. What are the equations? Let the mass be m. m=500 before the engine is fired and dm/dt = -10 after it is fired.

l l

l l

Moon Lander Continued


the altitude be H and the downwards velocity be v. We all know Newtons second law, F = ma? dh/dt = -v at all times Before the engine is fired dv/dt = g = 1 After firing dv/dt = g 5000/m The Problem: When do you fire the engine to achieve a soft landing? l So lets do it!
l Let
l

What do we do?
Write a Derivative Script - like derivp2 but more complex. Write a main program like Lubeplt2 but (a bit) Get some insight into the solution. Figure out how to answer the question. We will work on this until its done.

l l l l

Software and Computing I

Page 10

Some Exercises
4.1.1 The script that finds nCr given in lectures will fail for large values of n and/or r. What is the largest nC2 that it can find? Why? Find a recurrence for computing nCr from nCr-1, and write a script that uses it. With the recurrence, how large can n and/or r be before it fails? Why? 4.1.2 Revisit your program for computing Pascals triangle (Exercise 2.3.1) and improve the solution using loops and the recurrence from 4.1.1. How many rows could it calculate without the recurrence formula? How many rows can it now calculate? 4.1.3 You borrow money to finance your education. Repayments are at 6% per annum calculated monthly. (i) Find the minimum repayment that will eventually repay the loan. (ii) If your payments are 10% more than the minimum, how long will it take to repay it, and what total sum will you have repaid? You can do this by theory or by trial and error. 4.1.4. Solve the Moon Lander Problem. How does the step size affect the answer. So what then is the correct time to turn on the Thrust? 4.1.5 MATLAB has lots of ODE solvers built into it. Try them on Moon Lander. Again look at the effect of the step size on the solution, and so - once again - what is the correct time to turn on the thrust?

More Exercises
4.1.5 MATLAB has lots of ODE solvers built into it. Try them on Moon Lander. Again look at the effect of the step size on the solution, and so - once again - what is the correct time to turn on the thrust? 4.1.6. An express train of Mass 500 Tons approaches a level crossing travelling at 80 miles per hour when the driver spots a 1 Ton Range Rover on the crossing. The Brakes exert a slowing force on the train which is 1 tons times the speed if the speed is over 10 miles Per hour, and a constant 1 ton if the speed is below 10 miles per hour. How far from the level crossing must the brakes be applied to stop before Lunching the Land Rover? 4.1.7 Solve the following chaotic ODE by Eulers method: dx/dt = 10(y-x) dy/dt = 48x - y - y*z dz/dt = x*y - 2.33z Experiment with t (start at .001). Graph the the solution if you like with plot or plot3. MATLB has a built in ODE solver. With these equations, compare its accuracy with Eulers method. If t is large, what happens?

The while structure


l l

Example: Improved sine finder


% Recurrence for sin(x) % Keeps going until term < 2*eps % Give it x in radians, answer in sine % Notice that its silent % D. M. Monro 6 Oct 1997 sine = x; term =x; pow = 3; while abs(term ) > 2*eps term = -term * x^2 / (pow*(pow-1)); sine = sine + term; pow = pow + 2; end

while expression any series of statements end If expression is nonzero, the statements are repeated until expression becomes zero. Testing is done each time at the beginning Example:
j=1 while j<11 statements j=j+1 end % This is just like for j = 1:10 !! % OK, Ill explain this soon

Logical expressions
l

The if command:
if expression commands end Carries on

MATLAB can evaluate Logical Expressions value logical operation value The result is either 0 (False) or 1 (True) The operations available are: < less than <= less or equal > greater than >= greater or equal == exactly equal ~= not exactly equal & AND | OR ~ NOT xor exclusive OR

These operations also have a precedence, among themselves and with the Arithmetic Operators.

If the expresison is 1, the commands are executed, otherwise they are skipped over

Software and Computing I

Page 11

Think about this:

if with else if or else


if expression 1 commands 1 else if expression 2 commands 2 else if expression 3 : end At most one set of commands is done, might not be any.

if First > Second Temp = First; First = Second; Second = Temp; end

if expression 1 commands 1 else if expression 2 commands 2 else if expression 3 : else final expression end Exactly one set of commands is done.

Nested structures
l l l l l

PlotTwoThings is like a Double CoolTab


function PlotTwoThings(s1, s2) fprintf('\n') % For 2004 Exam for i = 1:First-1 % Its easy so why can no-one do it? fprintf(' ') First = round(s1); end Second = round(s2); fprintf('*') if First > Second if Second > First Temp = First; for i = First:Second-1 First = Second; fprintf(' ') Second = Temp; end end fprintf('*') end

Programs with if, while and for inside each other can become quite complex Each if, while or for structure must end with end Each end command is owned by the most recent if, while or for structure Indent each structure a few spaces Identify structures clearly with comments

Make a Graph of Two Things


% Display two Sines a1 = 1; % Amplitude of first sinusoid f1 = 1; % Frequency (Hz) of first sinusiod % Now make the display % Convert to radians; for i = 0:40 omega1 = 2*pi*f1; t = i*TimeStep; const = pi/180; s1 = a2 = 0.5; % Amplitude of second sinusiod 40+40*a1*sin(omega1*t+ f2 = 2; % Frequency (Hz) of second sinusiod phi1); omega2 = 2*pi*f2; s2 = % Want to cover 40 steps at lowest 40+40*a2*sin(omega2*t+ frequency phi2); TimeStep = 1/(40*f1); PlotTwoThings(s1, s2) if omega2<omega1 end TimeStep = 1/(40*f2); end

More Control Commands


break Leaves innermost for or while structure keyboard Goes to keyboard control, as if the keyboard were an m-file error(error message) Shows error message and goes to keyboard return leaves an m-file immediately quit terminates MATLAB

Software and Computing I

Page 12

Yet more Exercises


4.1.8 Look up the power series for cos x and write a cosine finder in MATLAB. Look at how many terms are used for different values of x, I.e. the rate of convergence. You know that cos is periodic, so how can you reduce x to the equivalent value in the range -pi to pi? How does that affect the convergence? 4.1.9 Write a log x finder by power series in MATLAB. How does its convergence compare with cos and sin. Why? Can it be improved? 4.1.10 In Moon Lander, add a loop to try different times for switching on the thrust, and detect when the answer is found. 4.1.11 Make Moon Lander or Express Train by Eulers method find the answer automatically. First of all find a Thrust On time which is too early (EarlyOn), and one that is too late (LateOn). Then compute what happens too early or too late if the Thrust On time is midway between, i.e. (EarlyOn+LateOn)/2. Now find the correct time by iteratively selecting the correct half and dividing it in half. That is called Binary Division. Where is the recurrence in this? Investigate the effect of the step size. How fast does it find the answer? Try a different ODE Solver. What really is the answer? Now at last you have written a Real Grown Up Program (RGUP) to solve a Real Grown Up Problem. Congratulations.

Yet more Exercises (continued)


4.1.12 Another RGUP. In the Moon Lander we solve a differential equation to find the Thrust On time by zooming in on the answer. but what we are doing is finding where the height becomes zero when the velocity is zero. Often we have a formula for a function f(x) = 0. We could use the Binary Division process to do that too. So find the roots of the polynomial f(x) = x^3 7.8x^2 + 18.5x 9.1 = 0 by Binary Division. Generalize you program to find the roots of any function. Will it always find a root? If there are multiple roots, which one will it find? 4.1.13 Yet another RGUP. Newtons method (also called NewtonRaphson) for root finding predicts the answer using the the slope of the function. You need only one guess to predict the next iteration using the slope. Try to work out the theory, then look it up. Write a root finder by this method. Compare its convergence with the binary search. What are the advantages and disadvantages of each method?

Functions and Scripts


l We

Input Parameter Passing


l To

have used script files by setting global variables and then invoking the script l This is ugly and silly! l A .m file that begins with the function command is better:
function[out1, out2, . . .] = funcname(in1, in2, . . .)

invoke a function you write

[reslt1, reslt2, . . .] = funcname(value1, value2, . . . .) MATLAB makes a local copy of the input values value1, value2, . . . for the function to use.
l In

the function

output list
l This

same name as .m file

input list

allows you to pass and receive values, and the function has private (local) variables

function[out1, out2, . . .] = funcname(in1, in2, . . .) MATLAB works with in1, in2, . . . which are the local copies of value1, value2, . . . l Anything you do to in1, in2, . . . affects only the local copy, and is NOT copied back to the invoking program UNLESS . . .

Passing Back Results


l Functions

with no outputs: e.g. function countdn(secs) or function [ ] = countdn(secs) l Functions with one output e.g. function chances = births(n) or function [chances] = births(n) l Functions with several outputs e.g. function [value, index] = demedian(array) l The function should assign values to the output variables. It is an error to invoke the function with incompatible variable lists.

function player % Play a music file Sound = 'Mozart'; [Source, Fs] = wavread(Sound); sound(Source, Fs)

player.m

hangabout.m
function Hangabout(secs) % Hang about for secs seconds % D. M. Monro 29 October 1999 % Start timer, and get the start time tic; start = toc; fprintf('\n Hangabout started at %-6.2f', start) stoptime = start + secs; while toc < stoptime end fprintf('\n Hangabout completed at %-6.2f \n', toc)

Software and Computing I

Page 13

showabout.m
function showabout(secs) % Hang about for secs seconds % D. M. Monro 29 October 1999 % Start timer, and get the start time tic; start = toc; fprintf('\n Showabout started at %-6.2f', start) stoptime = start + secs; while toc < stoptime % Display the time toc end fprintf('\n Showabout completed at %-6.2f \n', toc)

countdn.m
function countdn(secs) % Count down for secs seconds % D. M. Monro 13 October 1997 tic; start = toc; finish = start + secs; then = fix(finish - toc); while toc < finish now = fix(finish - toc); if now ~= then fprintf('\n') fprintf('%-6i', now) then = now; end end fprintf('\n')

births.m
function chances = births(n) % births(n) computes the chances that at least 2 people % in a group of n all have the same birthday % D.M.Monro 13 October 1997 chances = 1-(364/365)^(n-1)^n;

from an old exam


1 (e) The binomial coefficient nCr might be computed in MATLAB as prod(1:n)/(prod(1:r)*prod(1:n-r)) but this would be inefficient and likely to fail for large values of n or r. (i) If values are represented by 16 bit twos complement integers, what are the largest values of n and r that can be used? (ii) A recurrence could be used to compute nCr from nCr-1. Derive the formula for this recurrence and write a MATLAB function to compute using it. Why is this approach better? [4 marks]

combs.m
function result = combs(n,r) % combs(n,r) computes the binomial coefficient nCr % i.e. the number of possible combinations of r % objects chosen from a supply of n different ones % D.M.Monro 29 September 1997 result = prod(n-r+1:n) / prod(1:r);

function [value, index] = demedian(array) % Find the median value and its index in the array % D. M. Monro 13 October 1997 [array,indices] = sort(array); where = length(array)/2; value = array(where); index = indices(where);

demedian.m

Local & Global Names


l l

Some Exercises
4.2.1 Write a function called isprime(n) to find out if a number n is prime. It should pass back the result 1 if n is prime or 0 if it is not. The function should deal sensibly with ANY value of n. 4.2.2 Write a program to use isprime(n) to find all prime factors of m. 4.2.3 Convert the three root fnding scripts from the previous section to functions. To make them general, they will need to invoke other functions to evaluate f(x), and in the case of the Newton method, the derivative of f(x). You could use specific function names, or you could find out how to pass the names of functions as parameters. Wow! 4.2.4 Revisit the Euler method and tidy your programs into functions. The same problem arises as in 3.1.1 over the names of functions to define the derivatives. Euler is not the greatest ODE Solver many other more advanced ones exist, the most famous being Runge-Kutta. 4.2.5 Given a value h1, find h2, h3 and h4 such that three conditions are met: (I) sum hi^2=1, (ii) sum hi = 2^(1/2), and h1h3+h2h4 = 0. Congratulations, you have designed an orthonormal wavelet!

In your workspace and script files, all variable names are shared, i.e. are known globally. In a function, all variable names are local. The function cant see your workspace variables unless you force it to with the global command: global name1, name2, . . . We are going to use it later to do simple object based programming Data is copied back by assigning values to the output list, OR by using global names.

Software and Computing I

Page 14

5. Arrays and Graphs ~ 4 Lectures


l 5.1

Arrays and Subscripts


l

An Array of length n is a list of n values:

Introducing Arrays l 5.2 Summing and Searching in Arrays l 5.3 Array Manipulation l 5.4 Array Operations

- One name is used forthe whole list - A particular value is accessed by its subscript - It is really a 1xn matrix (I.e. a row matrix)

l l l

Arrays are also called Vectors Subscripts are also called Indices Example:
for place = 1:10 Arry(place) = 11 - place; end Arry

Arry(place) = 11 - place

Array Index Name

New Value

Flashy Definitions
l

Array Creation Commands


l MATLAB

You can define the contents of an array by placing a list of values in square brackets: Arry = [1 2 3 4 5 6 7 8 9 10] This gives values to Arry and sets its length Arry = [] is an empty array And theres this: Arry = [1:10] or Arry = 1:10 first:step:last was used in the for command. It makes a list of linearly spaced values.

has a number of functions which set up special arrays: A = [] %Null or empty array A = zeros(1,num) %Array of num zeroes A = ones(1,num) %Array of ones A = rand(1, num) % Uniform random values A = randn(1, num) % Gaussian randoms A = linspace(x1, x2) or linspace(x1, x2, N) A = logspace(d1, d2) or logspace (d1, d2, N) See MATLAB help for linspace and logspace.

Plotting Functions like y = f(x)


l l

Some Other Graph Types


l

l l

MATLAB has many commands for graphics. To plot a function like y=f(x), calculate a vector of yvalues and then use: plot(y) %Plot y values against indices Or define an x vector also and use plot(x, y) %Plot y versus x Also available plot(x, y, style) for example plot(x, y, r:) %Plot is red dashed line Use MATLAB help plot to find out more

l l l

MATLAB supports different graph styles. These are used just like plot: bar hist stem stairs comet semilogx semilogy loglog Slightly different: fplot polar Start a new graph with figure or figure(num) Use multiple plots on same axis with hold hold or hold on Add graphs to current plot hold off When finished Experiment and use help to find out more

Software and Computing I

Page 15

Some Useful Functions


l 5.2

Summing and Searching in Arrays


lSome

Useful Functions lExample: Where is Max? lSumming or Scanning lExample: Histograms lExample: Sorting lSome Exercises

l MATLAB

has zillions of functions for arrays and matrices. Here are a few: l length size min max sum prod mean std sort median l Always check exact details with help, e.g.
>> help length %LENGTH Number of components of a vector. % LENGTH(X) returns the length of vector X. It is equivalent % to MAX(SIZE(X)). % Copyright (c) 1984-94 by The MathWorks, Inc. % Built-in function.

Example: Where is Max?


OK, MATLAB has a command max, but here we illustrate array scanning by writing our own.
function [maxval, maxindex] = getmax(Arry) % Finds maximum value maxval and its % first encounter index maxindex in vector Arry % D. M. Monro 4 November 1997 % Get length and check it % Now scan the rest len=length(Arry); for indx=2:len if len == 0 if Arry(indx)>maxval % Array is empty, report error % A new maximum is found error('Empty Array in getmax, TTFN') maxval = Arry(indx); end maxindex = indx; % Use sensible initial value for maximum end % of recording new maximum maxval = Arry(1); maxindex = 1; end % of the scanning loop

Summing or Scanning
Many calculations follow this pattern of iteration. It might be controlled by a while or for loop:
% Find the maximum - sensible initial value maxval = Arry(1); maxindex = 1; % Now scan the rest for indx=2:len if Arry(indx)>maxval % A new max is found - record it maxval = Arry(indx); maxindex = indx; end % of recording new maximum end % of the scanning loop

Initialize

finished?

? recurrence

Example: Histograms
function hstdemo(HowMany, Bins) % Discovering Histograms % D. M. Monro 4 Nov 1997 % Histogram of HowMany Random Numbers in Bins bins close all Rand1 = rand(1, HowMany); hist(Rand1 - 0.5, Bins) figure % Histogram of HowMany Gaussian numbers Rand2 = randn(1,HowMany); hist(Rand2, Bins) for index = 1:HowMany % Now sums of 12 randoms - eh? Rand3(index) = sum(rand(1,12))-6; Rand3 = zeros(1,HowMany); end figure hist(Rand3, Bins)

Example: Sorting
Sorting is an important process on computers the one by which a list of values is put into ascending or descending order. The simplest, and most obvious, sorting algorithm is the Bubble Sort. In it, the array is scanned from left to right, comparing adjacent values and switching them over if they are out of order. If you do this scan as many times as there are numbers in the array, you can be sure they are in order.

Software and Computing I

Page 16

The Program BubSort


function In = BubSort(In) % Bubble Sort the input Array In % D M Monro November 2005 close all show = 0; len = length(In); % make as many passes as there are datas for pass = 1:len for ind = 1:len-1 % And (maybe) graph it if In(ind) > In(ind+1) if show % Swap them figure temp = In(ind); plot(In) In(ind) = In(ind+1); keyboard In(ind+1) = temp; end end end end

Test BubSort
% Script file to test Bubble Sort % D M Monro November 2005 Trials = 1000 DataLength = 10 for i = 1:Trials a = fix(20*rand(1,DataLength)); b = BubSort(a); % Use our Bubble Sort bb = sort(a); % Use MATLAB Sort err = sum(b~=bb); if err > 0 error('Bubble Sort failure, sorry') end end fprintf('Bubble Sort succeeded %u times', Trials)

Some Exercises
5.2.1 Write a MATLAB function to find the minimum value in an array. Give as outputs both the value and the position where it first occurs. 5.2.2 The hist command draws a histogram, but does not give you the histogram as an array. Write a function which takes as input an array of values, a minimum value, a maximum value and the number of bins to use in between. Compute the histogram - a new array whose length is the number of bins and whose contents count the number of given values in each bin. Divide each bin by the total length of the original array to get a Probability Density Function (PDF), and pass the PDF back. Plot it with a suitable graphics command. 5.2.3 The entropy of a symbol s from a message source in bits is p(s) * log2 p(s), where p(s) is the probability of the symbol occurring in all messages. (This tells you tne minimum number of bits required to transmit the symbol. Never mind how.) The entropy of the source is then the sum of the individual entropies. Write a MATLAB function to calculate the individual and total entropies of an array of probabilities. 5.2.4 You receive a real message from the source. Write a MATLAB function that calculates the entropy of the message.

l 5.3

Array Manipulation
lFlashy

Indexing FIFO and LIFO lFIFO .m files - object based! lAnother object based example - Turtle Graphics lMaking Space for an Array lSome Exercises
lExample:

Flashy Indexing
l

Example: FIFO and LIFO


First In First Out
Put Push

The range construction can be used to select any part of an array. Examples: A = 1:10 % Define the array A(:) % All of the array A(2:9) % Eight values from array A(1:2:10) % Odd numbered indexes B = 3:8 % Another array A(B) % Wow! C = A>5 % Sneak Preview A(C) % Double Wow!

Last In First Out


Pop

Get

Software and Computing I

Page 17

FIFO .m files - object based!


The array FIFO is shared by three functions which use it
function newfifo % Initialize FIFO queue % D. M. Monro 9 Nov 1997 global FIFO FIFO=[]; function putfifo(value) % Add value to the FIFO Queue % D. M. Monro 9 Nov 1997 global FIFO FIFO=[ value FIFO ] function outvalue = getfifo % Retrieve value from FIFO Queue % D. M. Monro 9 Nov 1997 global FIFO len = length(FIFO) % Check for empty FIFO if len < 1 fprintf('No data in FIFO - NaN returned') outvalue = NaN else % It's OK, get value and shorten queue outvalue = FIFO(len) FIFO = FIFO(1:len-1) end

Object Based Example: Turtle Graphics


A `turtle graphics system is used to create line drawings. Conceptually, the turtle moves around on the page facing in a particular direction with its tail acting as a pen, which can either be in the up (not drawing) or down (drawing a line) positions. (a) What attributes of the turtle will the system have to remember? Write the MATLAB function NewTurt which initializes the system for drawing. ( 6 Marks) (b) Write these MATLAB functions to control the turtles attributes: TurnTo(Theta)%Turns the turtle to face in direction theta degrees TurnBy(Theta)%Turns the turtle by theta degrees clockwise PenUp % The turtle stops dragging its tail PenDn % The turtle starts dragging its tail ( 8 Marks) (c) Write the MATLAB functions which actually do the drawing: MoveTo(X, Y) % The turtle moves to position (X,Y) MoveBy(Distance) % The turtle moves forward the specified distance) NewPage % Start a new graphics window To draw a line from (X0, Y0) to (X1, Y1) in the current graphics window, you can use the low level MATLAB command: line( [X0 X1] , [Y0 Y1] )

Object Based Example: Turtle Graphics


The answer: (a)

Object Based Example: Turtle Graphics


The answer: (b)
function TurnTo(Theta) % Turn to face in direction Theta degrees global XTurt YTurt ThetaTurt PenTurt ThetaTurt = Theta;

function NewTurt % Initialize turtle graphics global XTurt YTurt ThetaTurt PenTurt XTurt = 0; YTurt = 0; ThetaTurt = 0; PenTurt = 0;

function PenUp % Lift the Pen function TurnBy(Theta) % Turn the Turtle by Theta degrees global XTurt YTurt ThetaTurt PenTurt ThetaTurt = ThetaTurt + Theta; global XTurt YTurt ThetaTurt PenTurt PenTurt=0;

function PenDn % Drop the Pen global XTurt YTurt ThetaTurt PenTurt PenTurt=1;

Object Based Example: Turtle Graphics


The answer: (c)
function MoveTo(X, Y) % Move the Turtle to (X, Y) global XTurt YTurt ThetaTurt PenTurt % Draw if the pen is down if PenTurt line( [XTurt X], [YTurt, Y] ) end % And update the pen position XTurt = X; YTurt = Y; function MoveBy(Distance) % Move by Distance in the direction faced global XTurt YTurt ThetaTurt PenTurt % Compute destination - get angle in radians ThetaRad = ThetaTurt*pi/180; X = XTurt + Distance * cos(ThetaRad); Y = YTurt + Distance * sin(ThetaRad); Moveto(X,Y) l l l l

Making Space for an Array


Usually you do not have to make space for an array, MATLAB extends it when necessary. In the FIFO example, the array grows and shrinks as the FIFO is used. However sometimes it may be necessary to restart it, hence the function newfifo, which makes sure FIFO is empty: FIFO = [] It may be necessary to set or change an arrays length. One way is to make it all os: In = zeros(1,100)

Software and Computing I

Page 18

Some Exercises
5.3.1 Do the LIFO. 5.3.2. Think of a way of using several LIFOs for sorting. Implement it. 5.3.3. Write a MATLAB function to shift the entries in an array n positions to the right (higher subscripts). Lose the values that are shifted out. Fill the vacated part with zeros. Then do left also. This could be a new function, or the same one in which n is negative. These functions should not fail if n is (I) zero or (ii) greater than the length oif the array. 5.3.4. Now rotate an array. In rotating right, the values that are shifted out at the right should come back in at the left end. Do both directions. 5.3.5. Write a MATLAB function to reverse the entries in an array. Be sure it does not fail for zero length, and works for both odd and even length. 5.3.6. Create functions to manage an object based histogram to which values can be added or removed. You need functions to initialize the histogram, to add a value to the histogram and one to delete a value. This will be useful in doing Exercise 5.4.2.

Whole Array Arithmetic


Whole Arrays: To add or subtract Arrays must be the same length. The result is again the same length: A + B is [ A(1)+B(1) A(2)+b(2) etc. ] l You can Mutiply, Divide or Power an array by a single value: A/4 is [ A(1)/4 A(2)/4 etc. ] l Multiply, Divide or Power between whole arrays are an error (but are matrix operations) l Element by Element The operations .* ./ and .^ are used to make a new array with point by point arithmetic, e.g. A .* B is the same as [ A(1)*B(1) A(2)*B(2) etc. ]
l

Whole Array Comparisons


l

Some Exercises
5.4.1 The median filter selects the mid value of n (n is usually odd) centred on the one being filtered. MATLAB has a median function. It works by first sorting the n values and then selecting the median. For example, if n is 5, the output is the 3rd value in sorted order. Experiment with this so you know how it works. You will see that median does not filter near the ends of an array - so write a median filter that does work there. 5.4.2 The MATLAB median filter is slow. Try a big one and see. However if you have a histogram, you can find the median quite quickly. So add to your object based histogram builder (Exercise 4.3.4) a function to extract the median of the values in the histogram. With it you can do median filtering by sliding your histogram maker along the array, each time adding a new value and deleting an old one. Think about efficient ways of finding the median of your histogram.

l l l

MATLAB can evaluate Logical Expressions with arrays: value logical operation value The result is either 0 (False) or 1 (True) If the values are Arrays, they must be the same length The result is an array of the same length with 1s where the result is true and 0s where it is not A special indexing facility allows you to extract the true values, again the lengths must match: C = A>5 % Sneak Preview A(C) % Double Wow! Look back - this was shown as an indexing option

6. Matrices and Pictures


l 6.1

Matrices and Subscripts


l l l l

Introducing Matrices
Matrices and Subscripts Flashy Definitions l Matrix Creation Commands l Which Way is Up? l Lets find out . . . l The RNSR is: l Visualizing Matrices: z = f(x,y) l The Mandelbrot Set l Some Exercises
l l

We know many things about Matrices already All values in MATLAB are Double Precision Complex Matrices It is just like an arrray with two subscripts Example:
for isub = 1:1:32 for jsub = 1:1:64 Mtrx(isub, jsub) = (isub-24)^2 + (jsub-48)^2; end end Mtrx

l 6.2 l 6.3

Using Matrices - Equation Solving Mask & Vector Calculations

Matrix Indices Name (Subscripts)

New Value

Software and Computing I

Page 19

Flashy Definitions
l

Matrix Creation Commands


l

l l

You can define a matrix by values in square brackets, with semicolons between rows: Mat = [1 2 3 4; 5 6 7 8; 9 10 11 12] This gives values to Mat and sets its length Mat = [] is an empty matrix And theres this: Mat = [1:4; 5:8; 9:12] Not to mention this: Mat = [ 1:4 5:8 9:12 ]

MATLAB has a number of functions which set up special arrays: Mat = [] %Null or empty matrix Mat = zeros(m,n) % m x n matrix of zeroes Mat = zeroes(m) % m x m matrix of zeroes Mat = ones(m, n) % m x n matrix of ones Mat = ones(m) % m x m matrix of ones Mat = eye(m, n) % m x n, 1s on diagonal Mat = eye(m) % m x m, 1s on diagonal Mat = rand(m, n) % Uniform random values Etc . . see help elmat and help specmat

Which way is up?


l

Lets find out . . .


% Make a function Mtrx = zeros(32, 64); for isub = 1:1:32 for jsub = 1:1:64 Mtrx(isub, jsub) = (isub-24)^2 + (jsub-48)^2; end % Now let's look at it in several ways end close all % Invert it and scale 0 - 63 subplot(2,2,1) Big = max(max(Mtrx)); contour(Mtrx) Mtrx = 63*(Big - Mtrx)/Big; subplot(2,2,2) pcolor(Mtrx) subplot(2,2,3) surf(Mtrx) subplot(2,2,4) image(Mtrx)

The standard definition of a m x n Matrix A is : A11 A12 A13 A14 . . . A1n A21 A22 A23 A24 . . . A2n : : Am1 Am2 Am3 Mm4 . . . Amn But! Which way round are graphics and images? Is it A(x,y) or A(y,x) or even A(-y,x)? Lets find out . . .

The RNSR is:


l

The standard definition of a m x n Matrix A is : A11 A12 A13 A14 . . . A1n A21 A22 A23 A24 . . . A2n : : Am1 Am2 Am3 Mm4 . . . Amn But! Which way round are graphics and images? Is it A(x,y) or A(y,x) or even A(-y,x)? The RNSR is A(y,x) for Graphics (Matrix upside down) A(-y,x) for images (Looks like the Matrix)

Think of it as F(v, h) Visualizing Matrices: z = f(v,h)


l l l l l l l

There are several commands for showing the contents of a Matrix Z as Z = f(v,h) As a contour map: contour(Z) or contour3(Z) (lots of variations) As a pseudocolour map pcolor(Z) As surface in perspective surf (Z) or surfc(Z) or surf1(Z) As mesh in perspective mesh, meshc, mesh1 As an image image(Z). Remember this shows the Matrix Upside Down As always - use help to find out more

Software and Computing I

Page 20

The Mandelbrot Set


Consider this iteration:
2 Z n = Z n 1 + C
Where Z and C are complex For what values of C does it converge? This can only be solved by trying it on a computer

Explore the Space of C


% Run C from MinC+i*MinC to MaxC+i*MaxC for RealMesh = 1:MeshSize RealC = MinC + DeltaC*(RealMesh-1) % Define the Space of C MeshSize=20, MinC = -1, MaxC = 1, for ImagMesh=1:MeshSize DeltaC = (MaxC-MinC)/(MeshSize-1); ImagC = MinC + DeltaC*(ImagMesh-1); Z=0; % Controls over the Iteration C=RealC + i*ImagC; MaxIters=100, Fence = 5, % Now the Iteration % Initialize everything for Iters = 1:MaxIters Inside = ones(MeshSize); Z = Z^2 + C; % Draw the Mandelbrot Set end close all Inside(ImagMesh, RealMesh) = abs(Z)<Fence; end end figure colormap('Primary') image(Inside*8) % D M Monro 1 December 1998

6.1.1 For the Mandelbrot set, investigate the range of C, the number of iterations and the position of the fence as before. Try colouring the image by the number of iterations taken to jump the fence. Zounds! 6.1.2 Another type of fractal is the so-called Julia set. Consider the same iteration zi = zi-12 + c, where z and c are complex. Suppose the image represents a region in the complex plane. For every z in that region, you want to know if the iteration converges, or runs to infinity. You test this by carrying out a fixed number of iterations, and then testing to see if |z| > f, where f is a fence. If |z| has jumped the fence, colour it white. If z has not jumped the fence, colour it black. Try this for c = 0.5 + j0.55. Investigate the effect of the number of iterations and the position of the fence. Investigate the best region of z to explore to get pretty pictures. 6.1.3 Now instead of colouring the result in 4.2.1 white, colour it by the number of iterations it takes to jump the fence. Wow! 6.1.4 Find out how to solve the equation z^3 = 1 by Newtons method. Colour the space of starting values of z according to which of the three possible solutions the iteration approaches. The answer is: Yikes!

Some Exercises

l6.2

Using Matrices - Equation Solving


lMatrix lSolving

Arithmetic Equations

Matrix Arithmetic
l Suppose

S is scalar, I.e. a 1x1 matrix Mtrx+S Mtrx-S Mtrx*S Mtrx/S all work. l Suppose Matrix A is mxn and B is pxq: A+B or A-B are legal if m=p and n=p A*B is legal if n=p, result is mxq A^B is special - see references A/B means A*inv(B) l A^S means A*A*A . . . and A must be square l If A & are the same size, point by point ops: A.*B A./B A.^B A.^B Also many functions e.g. sqrt(A) conj(A) l Transposition A is an nxm Matrix such that A(m,n) = conj(A(n,m))

Solving Equations
l Inverse

of A exists if m=n and det(A) ~=0 Inv(A)*A = eye(m) l A system of Equations is (of course) A x = y where x and y are column vectors of the same size (r,1) l If A is rxr and det(A) ~= small, then the solution is (of course) x = A-1 y = inv(A)*y in MATLAB l If A is mxr, MATLAB will give the best fit solution for any value of m, I.e. a least squares fit: x = A\Y this is cool!

Software and Computing I

Page 21

Matrix Comparisons
l6.3

Mask and Vector Calculations

lMatrix

Comparisons lMatrix Logic lMatrix Masking lMore Fractal stuff lExercise - From a Previous Exam

l l l

MATLAB can do comparisons of matrices Matrix1 compare operation value (or value logical operation Matrix1) The result is a matrix of 0 (False) or 1 (True) values The comparisons available are: < less than <= less or equal > greater than >= greater or equal == exactly equal ~= not exactly equal These operations also have a precedence, among themselves and with the Arithmetic Operators. If the value is a matrix, both must be the same size The result is a matrix of the same size as Matrix1 with 1s where the result is true and 0s where it is not

Matrix Logic
l

Matrix Masking
l

Tricky: A Mask can select points in an array: % Demonstrate a Mask % Construct some data A = ones(10); for col = 1:10 A(:,col) = A(:,col)*col; end A C = ones(10); % Make a Mask Mask = A>5 C(Mask) = A(Mask)

MATLAB can evaluate Matrix Logical Expressions: Matrix1 logical operation value (or value logical operation Matrix1) The result is a matrix of 0 (False) or 1 (True) values The logical operations available are: & AND | OR ~ NOT xor exclusive OR These operations also have a precedence, among themselves and with the Arithmetic Operators. If the value is a matrix, both must be the same size The result is a matrix of the same size as Matrix1 with 1s where the result is true and 0s where it is not
l

l l l

Size of Matrices and Masks must all be the same

Remember Mandelbrot
Consider this iteration:
2 Z n = Z n 1 + C
Where Z and C are complex For what values of C does it converge? This can only be solved by trying it on a computer

Mask and Vector Mandelbrot


% Draw the Mandelbrot Set % D M Monro 1 December 1998 % Define the Space of C MeshSize=20, MinC = -1, MaxC = 1, DeltaC = (MaxC-MinC)/(MeshSize-1); % Controls over the Iteration MaxIters=100, Fence = 5, ShowSpace = 20, % Initialize everything [RealC ImagC] = Meshgrid(MinC:DeltaC:MaxC); C = RealC+ i*ImagC; Z = zeros(MeshSize); Inside = ones(MeshSize); close all % Now the Iteration for Iters = 1:MaxIters % Iterate wherever Z is inside the Fence Z(Inside) = Z(Inside).^2 + C(Inside); Inside = abs(Z)<Fence; % Show iterations separated by ShowSpace if(~rem(Iters,ShowSpace)) figure colormap('Primary') image(Inside*8) end

end

Software and Computing I

Page 22

Exercise
l From

Some Exercises
(a) In converting (R, G, B) values to (Y, U, V), the U and V matrices are often downsampled by a factor of two in each direction, so that each value in U and V corresponds to a 2x2 block of 4 values in Y, and is obtained by averaging the 4 values given by the conversion equations (Figure 1). There is no need to be concerned about the ranges of (Y, U, V) values. Write a function to perform this conversion, checking the input parameters for correct sizes and making maximum use of the matrix facilities of MATLAB: function [Y, U, V] = rgb_yuv(R, G, B) % Convert R, G, B image whose size must be even % to Y U V with U and V subsampled by averaging [10 marks]

a Previous Exam

Use Mask and Vectors in place of loops wherever possible 5 Coloured images are normally digitized and displayed as matrices of Red, Green and Blue values, so that each pixel is represented by corresponding values (R, G, B) from these matrices. In MATLAB it is normal for each of (R, G, B) to have minimum value of 0.0 and maximum value of 1.0 However for image processing, a different representation is almost always used, called (Y, U, V). Y represents the brightness of the picture, and U and V describe the colour in a compact way. In an image processing system, the transformation between these representations must be made. The relationship is: Y = 0.299*R + 0.587*G + 0.114*B U=B-Y V=R-Y

Some Exercises
(b) Now write the function to convert back again. First upsample the U and V matrices by repeating each value 4 times, and then convert back from (Y, U, V) to (R, G, B). This may introduce illegal values of R, G or B. If negative values occur, then all (R,G,B) values must be increased by the same amount so the smallest value is 0. Next, if any values are greater than 1.0, all (R, G, B) values must be multiplied by the same constant so that the maximum is 1.0. This process is called clipping. Write this function, checking the sizes of the input parameters and making maximum use of the matrix facilities of MATLAB: function [R, G, B] = yuv_rgb(Y, U, V) % Convert Y, U, V image to R G B. Size(Y) must be even % Sizes of U & V must be 1/2 size(Y) [10 marks]

Software and Computing I

Page 23

You might also like