Académique Documents
Professionnel Documents
Culture Documents
Unit EE10086 Given by: D. M. Monro (MATLAB) M. J. Balchin (SIMULINK) P. J. Leonard (Lab)
To understand the use of computers for: Solving Problems Making Calculations Manipulating Data Presenting Results
Structure of Lectures
l1 l2
20 - ish Lectures
l l l
Laboratory
2 Groups AB and CD
l l
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
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
Getting Started with MATLAB XX: A quick introduction for scientists and engineers, by R Pratrap, Oxford University Press, ISBN 0-19-512947
>>
l The
dialog is always: prompt command response >> You type this Matlab reacts l When you are finished, type exit or quit
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
8.8900
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?
we do it:
rem(n, 5) ans = 1 rem(n, 7) ans = 3 Is that necessary? Why?
2. Calculations ~ 3 Lectures
l2.1
Building MATLAB Programs l2.2 Arithmetic and MATLAB l2.3 Clean up your output
l2.1
l.m
Files lCreate, Edit and Save lComments and Help lSome Special Commands
Page 2
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.)
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 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
Page 3
What, No Integers?
l 2.2
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
Display Format
l Matlab
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
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
Page 4
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
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
functions
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.
Page 5
l2.3
lExample:
Find a Sine lScreen Output is untidy lExample - print a table lThe Format lInput from Keyboard
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?
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
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
Page 6
The Format
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
%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
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.
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
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
Adding up - iteration
l Iteration
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
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
maxterm=21; sine = x; term =x; for pow = 3:2:maxterm term = -term * x^2 / (pow*(pow-1)); sine = sine + term; end sine
l Suppose
dx = dt
l Euler
l l l
x(now + t) = x(now) + t * F(x) where t is the time step l If you apply this repeatedly, its a recurrence!
% 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
Page 9
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!
l l
l 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
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?
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
Page 11
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
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
Page 12
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, . . .)
[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
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 . . .
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)
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;
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
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.
Page 14
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
New Value
Flashy Definitions
l
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.
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
Page 15
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.
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.
Page 16
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
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!
Get
Page 17
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;
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.
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
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
New Value
Page 19
Flashy Definitions
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
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 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)
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
Page 20
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
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!
Page 21
Matrix Comparisons
l6.3
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
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
end
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]
Page 23