Top Banner

of 23

Matlab Notes 2005

Apr 07, 2018

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/4/2019 Matlab Notes 2005

    1/23Software and Computing I Pag

    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 20 - ish Lectures

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

    l Tutorials

    As required

    l 2 Hour Examination(January)

    l Weighting 50% of Unit

    l Laboratory2 Groups AB and CD

    l 3 hours Laboratory

    each week.

    l 2 Lab Assessmentsl Unequal weighting

    l Total 50% of Unit

    Note heavy weighting of Lab

    l Its hard work and its important!

    Structure of Lectures

    l 1 Introduction - this lecture

    l 2 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 You need a quick reference to supplement online help

    l So it is suggested that you buy (XX is the Version)

    lGetting Started with MATLAB XX: A quick introduction for

    scientists and engineers, by R Pratrap, Oxford University Press,

    ISBN 0-19-512947l More substantial references are

    lMastering Matlab XX, by D Hanselman & B Littlefield,

    Prentice Hall

    lMatlab XX for Engineers, by A Biran & M Breiner, Addison

    Wesley

    l Introduction to MATLAB XX for Engineers, by Palm, McGraw Hill

    Using MATLAB

    l Turn your computer on

    lDouble click the MATLAB icon:

    l You will get a prompt:

    >>

    l The dialog is always:

    prompt command response

    >> You type this Matlab reacts

    lWhen you are finished, type exitorquit

    MATLAB 6.1.lnk

  • 8/4/2019 Matlab Notes 2005

    2/23Software and Computing I Pag

    Getting Help

    lRefer to the text

    lUse online helpl As soon as you get a chance try out:

    help help topic lookfor keyword

    why what who

    where whos

    l If all else fails, ask an expert

    l in the lab please

    Simple Examples

    l As a calculator:

    1.27*7

    ans = 8.8900

    3 + 4 / 5

    ans = 3.8000

    22/7;

    l Something funny here ?

    l You can define

    variables:

    x = 1.27x = 1.2700

    7*x

    ans = 8.8900

    who

    Your variables are:

    ans x

    Something More CleverlWe are given a decimal integer n

    l Is it prime?

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

    l So we do it:

    n=31;

    rem(n, 2)

    ans = 1

    rem(n, 3)

    ans = 1

    rem(n, 5)

    ans = 1

    rem(n, 7)

    ans = 3

    Is that necessary?

    Why?

    Some ExercisesFind out about the fix function. Using only the rem and

    fix functions you can do these exercises usingMATLAB as a calculator with variables. You do notneed 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 chocolateson a layer and there are three layers. How manyboxes do I need to hold 4410 chocolates? 511chocolates? 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?

    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

    l

    Create, Edit and SavelComments and Help

    lSome Special Commands

  • 8/4/2019 Matlab Notes 2005

    3/23Software and Computing I Pag

    .m Files (Script Files)

    l A .m file or script file is a sequence of MATLABinstructions.

    l Suppose we want to compute nCr = n!/r!(n-r)!= n*(n-1)*(n-2) . . .(n-r+1) / r!

    l 1. Make a file called ncr.mIt contains one line of MATLAB:nCr = prod(n-r+1:n) / prod(1:r);

    l To use it, assign values to set n and r, and then enterthe name of the script file

    l Its also = n*(n-1)*(n-2) . . .(r+1) /( n-r)!

    Create, Edit and Save

    l Creat a script file by selecting New from the MATLAB

    file menul This calls up a nice MATLAB editor

    l Edit with keys and mouse:Learn how to place cursor with mouse or keys

    add and remove characterscut and paste text

    l Save the file as a meaningful name

    l Then MATLAB can use it

    l Remember to save it every time it is changed.(MATLAB 7 forces you.)

    Comments and Help

    lUse the % symbol to begin a comment

    l The comment continues to the end of the line

    lComments 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 lookforkeywordsearches the

    first line of every m-file in the path for the

    keyword, and displays the line if it finds it.

    Helpful Punctuationl To 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 access a command of the computersoperating system, use ! commandsuch as!dir

    l

    To see what directories are searched byMATLAB, use path

    l If there is a file called startup.m in the path, itwill be executed when you start MATLAB

    l So for example you can use path in startup.mto inform MATLAB about your directories

    Some Exercises2.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 areuseful to you already. Using help, find out what each of them does, andtry them.

    2.1.2 Write a script file that will tell you what the chances are that r peoplefrom 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 theright, and so on. Write a script file to calculate the new value when thisis done. Then do rotation left. Finally, try reversing the bits.

    2.1.4 The Reverend Zeller, in 1883, came up with a wonderful formula tohelp you with calendar calculations. The months in a year haveunequal numbers of days. If you assume each is 28 days long, thenZellers formula

    extras = fix ( (13*month-1)/5) - 2gives you the number of irregular days added on. Months are countedfrom 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 after1 March 1600 (which was a Wednesday or was it?)

  • 8/4/2019 Matlab Notes 2005

    4/23Software and Computing I Pag

    l 2.2 Arithmetic and MATLABl What, no Integers?

    l Display formatl Constants & Special Constants

    l Variables

    l Special Variables

    l Arithmetic Operators

    l Priority

    What, No Integers?

    l By Default MATLAB Values are Double Precision

    Complex Matrices Not really, but believe this anyway)

    l Double Precision means 64 bits, or about 14 decimalplaces.

    l

    eps is the smallest number:

    inf is the largest number:

    l So the largest value is?

    Display Format

    lMatlab 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

    Constants & Special Constants

    l To 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

    lGood and Bad News:

    lMatlab is Case sensitive:

    Nigel and nigel and NiGeL are NOT the same

    l The Really Bad News:

    l Spelling mistakes cannot be detected

    & Spelling mistakes can cause serious errors

  • 8/4/2019 Matlab Notes 2005

    5/23Software and Computing I Pag

    Special Variables

    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

    Arithmetic Operators

    l Add or subtract:

    A + B A - B - A + BlMutiply or Divide:

    A * B B * A A / B B / A

    Funny Division:

    A \ B B \ A

    lRaise to a Power:

    A ^ B

    Priorityl 3 + 4 * 5 could mean one of two things:

    (3 + 4) * 5 or 3 + (4 * 5)

    l Similarly, what do these mean:3 + 4 / 5 3 + 4 \ 5 6

    l The priority of operations is:high (done first) ^

    / or \ or *low (done last) + or -

    l You can work out the answer by placing bracketsaround groups of equal priority:A + B * C * D ^ E is (A + (B * C * (D^E)))

    Mathematical Functions

    l Trig 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 functions

    exp log log10 sqrt log2

    lComplex functions

    abs angle conj real imag

    Integers and Reals

    l Look at

    help elfun

    l Fixing and Rounding:

    You have already seen the functions

    fix(x) round towards zerorem(n,d) remainder of n/d

    lOthers you should know about:

    round round towards nearest integer

    floor round towards - inf

    ceil round towards inf

    sign answer -1, 0, or 1

    Some Exercises2.2.1 Before you try them, what do you expect from these MATLAB

    expressions:0 + eps 0 - eps inf + eps inf - epsrealmax + eps realmax - eps realmin - eps

    realmin + eps realmax - realmin realmin -realmaxrea lmin+ realmin realmax+ realmax0 + eps - eps realmax + eps - eps

    2.2.2 Now try all the above expressions in MATLAB, and explain in eachcase what MATLAB is doing.

    2.2.3 First predict by reasoning, and then confirm using MATLAB theresults 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 itout or look it up. use it to find the sum of all the numbers from 1 to1000.

  • 8/4/2019 Matlab Notes 2005

    6/23Software and Computing I Pag

    l2.3 Clean up your output

    lExample: Find a Sine

    lScreen Output is untidy

    lExample - print a table

    lThe Format

    lInput from Keyboard

    Input from Keyboard

    l The 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))

    lMATLABs screen output is untidy

    l You know that it can be silenced with the ;

    lNow you will see how to control preciselywhat it displays

    l . . . but you wont like i t!

    l The fprintf command does it:

    fprintf (format, values)

    You give one format in quotes and one list ofvalues separated by commas

    The values are displayed using the formatspecification

    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

    Examplel This is what it printed:

    Table of Compound InterestRate = 4% 6% 8% 10%

    Periods1 1.04 1.06 1.08 1.10

    2 1.08 1.12 1.17 1.213 1.12 1.19 1.26 1.334 1.17 1.26 1.36 1.465 1.22 1.34 1.47 1.616 1.27 1.42 1.59 1.777 1.32 1.50 1.71 1.958 1.37 1.59 1.85 2.149 1.42 1.69 2.00 2.3610 1.48 1.79 2.16 2.59

  • 8/4/2019 Matlab Notes 2005

    7/23Software and Computing I Pag

    The Formatl The formatis 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

    lControl specifications include:

    \n new line \t tab \b back 1 space

    \r return to beginning of l ine \\ print \

    \ or print %% print % \a irritating noise

    lMore details in any C manual

    The Format - Continuedl The conversion specification controls the

    exact layout of data. It takes the form:

    %- w .d Cl The - is optional and causes the field to be

    left justified

    The wis optional and specified the width of

    the field in characters

    The .dfollows a wand is also optional. It

    specifies the number of decimal places

    The Cspecifies the type of conversion

    Yet More Formatl Some 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

    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 Position on a new linefprintf('\n')

    for Cool = 1:Tab

    fprintf(' ')

    end

    Some ExercisesOfficially 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 bedone the hard way, I.e. without loops, and then (or later) see how muchneater a loop structure makes them:

    2.3.1 Write a program to print out 8 rows of Pascals Triangle which is atable of the values of nCr laid out as:

    0C0

    1C0 1C12C0 2C1 2C2

    (Note that the ends of the rows have value 1, and the others are the sumof 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, buthere the idea is to make the graph in the command window using onlyfprintf.

    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.

  • 8/4/2019 Matlab Notes 2005

    8/23Software and Computing I Pag

    4. Programming ~ 6 Lectures

    4.1 Control of Programsl Flow diagrams

    l The forloop - iterationl Power series - evaluating sines - recurrence

    l Solving Ordinary Differential Equations - Eulers method

    l The while structure

    l Logical expressions

    l The ifstructure

    l Example - finding roots

    l More control commands

    l Exercises

    l 4.2 Functions and Scripts

    The for loop

    l Start a MATLAB loop with for and end it with end:

    forvariable = start: step : finish

    any series of statementsend

    l The statements within the loop are repeated with the

    variable taking all the values from startto finish,

    separated by step

    l If no step is given, 1 is used

    l start: step : finish is a special kind of expression that

    occurs in other places

    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 is when a similar calculation isrepeated over and over

    l Example: Add the numbers from 1 to 10

    l So heres a program:

    summy = 1; %Initialisefor t = 1 to 10

    summy = summy+t; % add them up

    end

    summy

    Power Series - iteration again

    l We know

    sin x = x - x 3 + x^5 - x 7 + . . .

    3! 5! 7!

    l 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

  • 8/4/2019 Matlab Notes 2005

    9/23Software and Computing I Pag

    Recurrencel Observe

    sin x = term 1 + term 3 + term 5 + . . .and term n = (- term n-2 ) * x^2

    n * (n-1)

    l The above is a recurrence formula

    l So the program could bel maxterm=21;

    l sine = x; term =x;

    l for pow = 3:2:maxterm

    l term = -term * x^2 / (pow*(pow-1));

    l sine = sine + term;

    l end

    l sine

    l Why is this efficient? Can it be improved?

    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

    Eulers Method Tough Stuff!

    l Suppose I have a process described by

    dx = F(x) This is an Ordinary

    dt Differential Equation (ODE)

    l Euler 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!

    Example: Pint Inflation

    l Suppose the cost of a pint of beer is changing

    constantly by d pint = F(pint)

    dt

    l Euler saidpint(future) = pint(now) + time step * F(pint)

    l So if we know the present value and the rate of

    change, we can predict the future!

    l Example: Its going up r pence per unit of time

    l Example: Its going up r% per unit of time

    The Program Lubejob1.m% Lubejob1 solves 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

    p = start;

    t = 0;

    for step = 2:steps+1

    t = t + deltat;

    deriv1a; % deriv1a computes the slope

    p = p + deltat*deriv

    end

    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

    % Notice that t is not actually used in here.

    % So why bother with it?

    close all

    poft=start;

    parray=poft;

    t=0;

    for step = 2:steps+1

    t = t + deltat;

    derivp1a;

    poft = poft + deltat*deriv;

    parray = [parray poft];

    end

    plot(parray)

    parray

  • 8/4/2019 Matlab Notes 2005

    10/23Software and Computing I Page

    It could be more complicated

    l Suppose d^2 pint = F(pint) = 100 - pintdt ^2

    l To use Eulers prediction, we need the ODEto 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 - pintdt ^2

    l So lets do it!

    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

    % deltat = step size% startp1 = initial value of solution for p1

    % startp2 = initial value of solution for p2

    % Supply the file derivp2 to compute the time

    % derivative of the solution (p1, p2) at time t

    close all

    p1array = startp1; p1oft = startp1;

    p2array = startp2; p2oft = startp2;

    t = 0;

    for step = 2:steps+1

    step

    t = t + deltat;

    derivp2;

    % Do the Euler prediction

    p1oft = p1oft + deltat*dp1;p2oft = p2oft + deltat*dp2;

    % Save in the array

    p1array = [p1array p1oft];

    p2array = [p2array p2oft];

    end

    % Display the results

    taxis = [0:deltat:steps*deltat]

    plot(taxis,p1array)

    figure

    plot(taxis,p2array)

    figure

    plot(p1array,p2array)

    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;

    Moon Lander

    Third Order and Nonlinear

    l A spacecraft of mass 500 Kg approaching a moonhas an approach velocity of 100 metres per secondwhen it is at altitude 1000 metres. The accelerationdue to gravity on the moon is 1 m/s2.

    l When the rocket is fired it exerts a vertical force of5000 Newtons to slow the spacecraft.

    l But! The engine consumes 10 Kg of fuel per second,and there is only 50 Kg of fuel. So the mass of therocket starts to decreases when the rocket is fired.

    l What are the equations?

    l Let the mass be m. m=500 before the engine is fired

    and dm/dt = -10 after it is fired.

    l Let the altitude be H and the downwardsvelocity be v. We all know Newtons secondlaw, F = ma?

    dh/dt = -v at all timesBefore the engine is fired dv/dt = g = 1

    After firing dv/dt = g 5000/m

    The Problem: When do you fire the engine toachieve a soft landing?

    l So lets do it!

    Moon Lander Continued What do we do?

    l Write a Derivative Script - like derivp2 but morecomplex.

    l Write a main program like Lubeplt2 but (a bit)

    l Get some insight into the solution.

    l Figure out how to answer the question.

    l We will work on this until its done.

  • 8/4/2019 Matlab Notes 2005

    11/23Software and Computing I Page

    Some Exercises4.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 arecurrence 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? Howmany 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 willeventually repay the loan. (ii) If your payments are 10% more than theminimum, how long will it take to repay it, and what total sum will youhave 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 theanswer. 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 MoonLander. 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 Exercises4.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. Ift is large, what happens?

    The while structurewhile expression

    any series of statementsend

    l Ifexpression is nonzero, the statements are repeateduntil expression becomes zero.

    l Testing is done each time at the beginningExample:j=1 % This is just like for j = 1:10 !!

    whi le j 2*eps

    term = -term * x^2 / (pow*(pow-1));

    sine = sine + term;

    pow = pow + 2;

    end

    Logical expressions

    l MATLAB can evaluate Logical Expressionsvalue logical operation value

    The result is either 0 (False) or 1 (True)

    The operations available are:< less than greater than >= greater or equal== exactly equal ~= not exactly equal

    & AND | OR ~ NOT xor exclusive OR

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

    The if command:

    ifexpression

    commands

    endCarries on

    If the expresison is 1, the commands are

    executed, otherwise they are skipped over

  • 8/4/2019 Matlab Notes 2005

    12/23Software and Computing I Page

    Think about this:

    if First > Second

    Temp = First;

    First = Second;

    Second = Temp;

    end

    if with else if or elseifexpression 1

    commands 1

    else ifexpression 2

    commands 2

    else ifexpression 3

    :

    end

    At most one set ofcommands is done,might not be any.

    ifexpression 1

    commands 1

    else ifexpression 2commands 2

    else ifexpression 3

    :

    else

    final expression

    end

    Exactly one set of

    commands is done.

    Nested structures

    l Programs with if, while and for inside each other

    can become quite complex

    l Each if, while or for structure must end with end

    l Each end command is owned by the most recent

    if, while or for structure

    l Indent each structure a few spaces

    l Identify structures clearly with comments

    PlotTwoThings is like a

    Double CoolTabfunction PlotTwoThings(s1, s2)

    % For 2004 Exam

    % Its easy so why can no-one do it?

    First = round(s1);

    Second = round(s2);

    if First > Second

    Temp = First;

    First = Second;

    Second = Temp;

    end

    fprintf('\n')

    for i = 1:First-1

    fprintf(' ')

    end

    fprintf('*')

    if Second > First

    for i = First:Second-1

    fprintf(' ')

    end

    fprintf('*')end

    Make a Graph of Two Things

    % Now make the display

    for i = 0:40

    t = i*TimeStep;s1 =

    40+40*a1*sin(omega1*t+

    phi1);

    s2 =

    40+40*a2*sin(omega2*t+

    phi2);

    PlotTwoThings(s1, s2)

    end

    % Display two Sines

    a1 = 1; % Amplitude of first sinusoid

    f1 = 1; % Frequency (Hz) of first sinusiod

    % Convert to radians;

    omega1 = 2*pi*f1;

    const = pi/180;

    a2 = 0.5; % Amplitude of second sinusiod

    f2 = 2; % Frequency (Hz) of second sinusiod

    omega2 = 2*pi*f2;

    % Want to cover 40 steps at lowestfrequency

    TimeStep = 1/(40*f1);

    if omega2

  • 8/4/2019 Matlab Notes 2005

    13/23Software and Computing I Page

    Yet more Exercises4.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 canyou 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 onthe thrust, and detect when the answer is f ound.

    4.1.11 Make Moon Lander or Express Train by Eulers method find theanswer automatically. First of all find a Thrust On time which is tooearly (EarlyOn), and one that is too late (LateOn). Then compute whathappens too early or too late if the Thrust On time is midwaybetween, i.e. (EarlyOn+LateOn)/2. Now find the correct time byiteratively selecting the correct half and dividing it in half. That is calledBinary Division. Where is the recurrence in this? Investigate the effectof the step size. How fast does it find the answer? Try a different ODESolver. What really is the answer? Now at last you have written a RealGrown 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 f inding where the height becomes zero when the velocity iszero. 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 thepolynomial 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 alwaysfind a root? If there are multiple roots, which one will it find?

    4.1.13 Yet another RGUP. Newtons method (also called Newton-

    Raphson) 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 ScriptslWe 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 functioncommand is better:function[out1, out2, . . .] = funcname(in1, in2, . . .)

    output list same name input list

    as .m file

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

    Input Parameter Passingl To 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 functionfunction[out1, out2, . . .] = funcname(in1, in2, . . .)

    MATLAB works with in1, in2, . . . which are the local

    copies ofvalue1, value2, . . .

    l Anything you do to in1, in2, . . . affects only thelocal copy, and is NOT copied back to theinvoking 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 outputvariables. It is an error to invoke the function withincompatible variable lists.

    player.mfunction player% Play a music file

    Sound = 'Mozart';

    [Source, Fs] = wavread(Sound);

    sound(Source, Fs)

    hangabout.mfunction 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)

  • 8/4/2019 Matlab Notes 2005

    14/23Software and Computing I Page

    showabout.mfunction showabout(secs)

    % Hang about for secs seconds

    % D. M. Monro 29 October 1999

    % Start timer, and get the start timetic; 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.mfunction 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.mfunction chances = births(n)

    % births(n) computes the chances that at least 2 people

    % in a group of n a ll have the same birthday

    % D.M.Monro 13 October 1997

    chances = 1-(364/365)^(n-1) n;

    combs.mfunction 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);

    demedian.mfunction [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);

    from an old exam1 (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 ofn orr.

    (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]

    Local & Global Namesl In your workspace and script fi les, all variable names

    are shared, i.e. are known globally.

    l 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

    l Data is copied back by assigning values to the output

    list, OR by using global names.

    Some Exercises4.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 couldfind 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!

  • 8/4/2019 Matlab Notes 2005

    15/23Software and Computing I Page

    5. Arrays and Graphs

    ~ 4 Lectures

    l 5.1 Introducing Arrays

    l 5.2 Summing and Searching in Arrays

    l 5.3 Array Manipulation

    l 5.4 Array Operations

    Arrays and Subscripts

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

    - 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 Arrays are also called Vectors

    l Subscripts are also called Indices

    l Example:for place = 1:10

    Arry(place) = 11 - place;

    end

    ArryArry(place) = 11 - place

    Array Index New Value

    Name

    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

    l And theres this:

    Arry = [1:10] or Arry = 1:10

    first:step:lastwas used in the forcommand.

    It makes a list of linearly spaced values.

    Array Creation Commands

    lMATLAB has a number of functions which setup special arrays:A = [] %Null or empty arrayA = zeros(1,num) %Array of num zeroesA = ones(1,num) %Array of onesA = rand(1, num) % Uniform random valuesA = randn(1, num) % Gaussian randomsA = 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 MATLAB has many commands for graphics.

    l To plot a function like y=f(x), calculate a vector of y-values and then use:plot(y) %Plot y values against indices

    l Or define an x vector also and use

    plot(x, y) %Plot y versus xl Also available

    plot(x, y, style)for exampleplot(x, y, r:) %Plot is red dashed line

    l Use MATLAB help plot to find out more

    Some Other Graph Types

    l MATLAB supports different graph styles. These areused just like plot:bar hist stem stairs cometsemilogx semilogy loglog

    l Slightly different:

    fplot polar l Start a new graph with figure orfigure(num)

    l Use multiple plots on same axis with holdhold orhold on Add graphs to current plothold off When finished

    l Experiment and use help to find out more

  • 8/4/2019 Matlab Notes 2005

    16/23Software and Computing I Page

    l5.2 Summing and Searching in Arrays

    lSome Useful Functions

    l

    Example: Where is Max?lSumming or Scanning

    lExample: Histograms

    lExample: Sorting

    lSome Exercises

    Some Useful Functions

    lMATLAB has zillions of functions for arraysand matrices. Here are a few:

    llength size min maxsum prod mean stdsort 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 weillustrate 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

    len=length(Arry);

    iflen== 0

    % Array is empty, report error

    error('Empty Array in getmax, TTFN')

    end

    % Use sensible initial value for maximum

    maxval = Arry(1);

    maxindex = 1;

    % Now scan the rest

    for indx=2:len

    if Arry(indx)>maxval

    % A new maximum is found

    maxval = Arry(indx);

    maxindex = indx;

    end % of recording new maximum

    end % of the scanning loop

    Summing or ScanningMany 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: Histogramsfunction hstdemo(HowMany, Bins)% Discovering Histograms% D. M. Monro 4 Nov 1997

    % Histogram of HowMany Random Numbers in Bins binsclose allRand1 = rand(1, HowMany);hist(Rand1 - 0.5, Bins)figure

    % Histogram of HowMany Gaussian numbers

    Rand2 = randn(1,HowMany);

    hist(Rand2, Bins)

    % Now sums of 12 randoms - eh?

    Rand3 = zeros(1,HowMany);

    for index = 1:HowMany

    Rand3(index) = sum(rand(1,12))-6;

    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 algorithmis 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.

  • 8/4/2019 Matlab Notes 2005

    17/23Software and Computing I Page

    The Program BubSortfunction In = BubSort(In)

    % Bubble Sort the input Array In

    % D M Monro November 2005

    close allshow = 0; len = length(In);

    % make as many passes as there are datas

    for pass = 1:len

    forind = 1:len-1

    if In(ind) > In(ind+1)

    % Swap them

    temp = In(ind);

    In(ind) = In(ind+1);

    In(ind+1) = temp;

    end

    end

    % And (maybe) graph it

    if show

    figure

    plot(In)

    keyboard

    end

    end

    Test BubSort% Script file to test Bubble Sort

    % D M Monro November 2005

    Trials = 1000

    DataLength = 10for 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. Giveas 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 thehistogram as an array. Write a f unction which takes as input an array ofvalues, a minimum value, a maximum value and the number of bins touse in between. Compute the histogram - a new array whose length isthe number of bins and whose contents count the number of givenvalues in each bin. Divide each bin by the total length of the originalarray to get a Probability Density Function (PDF), and pass the PDFback. 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 allmessages. (This tells you tne minimum number of bits required totransmit the symbol. Never mind how.) The entropy of the source isthen the sum of the individual entropies. Write a MATLAB function tocalculate the individual and total entropies of an array of probabilities.

    5.2.4 You receive a real message from the source. Write a MATLABfunction that calculates the entropy of the message.

    l 5.3 Array Manipulation

    lFlashy Indexing

    lExample: FIFO and LIFO

    lFIFO .m files - object based!

    lAnother object based example - Turtle

    Graphics

    lMaking Space for an Array

    lSome Exercises

    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 arrayA(1:2:10) % Odd numbered indexes

    B = 3:8 % Another array

    A(B) % Wow!

    C = A>5 % Sneak Preview

    A(C) % Double Wow!

    Example: FIFO and LIFO

    First In First Out Last In First Out

    Put

    Get

    PopPush

  • 8/4/2019 Matlab Notes 2005

    18/23Software and Computing I Page

    FIFO .m files - object based!

    function newfifo

    % Initialize FIFO queue

    % D. M. Monro 9 Nov 1997

    global FIFO

    FIFO=[];

    function putfifo(value)

    % Add value to the FIFOQueue

    % 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

    iflen< 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

    The array FIFO is shared by three functions which use it

    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 asa 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] )

    function NewTurt

    % Initialize turtle graphics

    global XTurt YTurt ThetaTurt PenTurt

    XTurt = 0;

    YTurt = 0;

    ThetaTurt = 0;

    PenTurt = 0;

    Object Based Example: Turtle Graphics

    The answer: (a)

    function PenUp

    % Lift the Pen

    global XTurt YTurt ThetaTurt PenTurt

    PenTurt=0;

    function PenDn

    % Drop the Pen

    global XTurt YTurt ThetaTurt PenTurt

    PenTurt=1;

    function TurnTo(Theta)

    % Turn to face in direction Theta degrees

    global XTurt YTurt ThetaTurt PenTurt

    ThetaTurt = Theta;

    function TurnBy(Theta)

    % Turn the Turtle by Theta degrees

    global XTurt YTurt ThetaTurt PenTurt

    ThetaTurt = ThetaTurt + Theta;

    Object Based Example: Turtle GraphicsThe answer: (b)

    function MoveTo(X, Y)

    % Move the Turtle to (X, Y)

    global XTurt YTurt ThetaTurt PenTurt

    % Draw if the pen is down

    if PenTurtline( [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 inradians

    ThetaRad = ThetaTurt*pi/180;X = XTurt + Distance * cos(ThetaRad);

    Y = YTurt + Distance * sin(ThetaRad);

    Moveto(X,Y)

    Object Based Example: Turtle GraphicsThe answer: (c)

    Making Space for an Array

    l Usually you do not have to make space for an array,MATLAB extends it when necessary.

    l In the FIFO example, the array grows and shrinks asthe FIFO is used.

    l However sometimes it may be necessary to restart it,

    hence the function newfifo, which makes sure FIFO isempty:FIFO = []

    l It may be necessary to set or change an arrayslength. One way is to make it all os: In =zeros(1,100)

  • 8/4/2019 Matlab Notes 2005

    19/23Software and Computing I Page

    Some Exercises5.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. Fillthe vacated part with zeros. Then do left also. This could be a newfunction, 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 Arithmeticl 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. ]

    Whole Array Comparisons

    l MATLAB can evaluate Logical Expressions witharrays:

    value logical operation valueThe result is either 0 (False) or 1 (True)

    l If the values are Arrays, they must be the samelength

    l The result is an array of the same length with 1swhere the result is true and 0s where it is not

    l A special indexing facility allows you to extract thetrue values, again the lengths must match:C = A>5 % Sneak PreviewA(C) % Double Wow!

    l Look back - this was shown as an indexing option

    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 selectingthe 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 f ind 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.

    6. Matrices and Picturesl 6.1 Introducing Matrices

    l Matrices and Subscripts

    l 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 6.2 Using Matrices - Equation Solving

    l 6.3 Mask & Vector Calculations

    Matrices and Subscripts

    l We know many things about Matrices already

    l All values in MATLAB are Double Precision Complex

    Matrices

    l It is just like an arrray with two subscripts

    lExample:forisub = 1:1:32

    for jsub = 1:1:64

    Mtrx(isub, jsub) = (isub-24)^2 + (jsub-48)^2;

    end

    end

    Mtrx

    Matrix Indices New Value

    Name (Subscripts)

  • 8/4/2019 Matlab Notes 2005

    20/23Software and Computing I Page

    Flashy Definitions

    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 lengthMat = [] is an empty matrix

    l And theres this:Mat = [1:4; 5:8; 9:12]

    l Not to mention this:

    Mat = [ 1:4

    5:8

    9:12 ]

    Matrix Creation Commands

    l MATLAB has a number of functions which set upspecial arrays:Mat = [] %Null or empty matrix

    Mat = zeros(m,n) % m x n matrix of zeroesMat = zeroes(m) % m x m matrix of zeroesMat = ones(m, n) % m x n matrix of onesMat = ones(m) % m x m matrix of onesMat = eye(m, n) % m x n, 1s on diagonalMat = eye(m) % m x m, 1s on diagonalMat = rand(m, n) % Uniform random values

    Etc . . see help elmatand help specmat

    Which way is up?

    l The standard definition of a m x n Matrix A is :A11 A12 A13 A14 . . . A1nA21 A22 A23 A24 . . . A2n: :Am1 Am2 Am3 Mm4 . . . Amn

    l But!Which way round are graphics and images?

    Is it A(x,y) or A(y,x) or even A(-y,x)?

    l Lets find out . . .

    Lets find out . . .% Make a function

    Mtrx = zeros(32, 64);

    for isub = 1:1:32

    forjsub = 1:1:64

    Mtrx(isub, jsub) = (isub-24)^2 + (jsub-48)^2;

    end

    end

    % Invert it and scale 0 - 63

    Big = max(max(Mtrx));

    Mtrx = 63*(Big - Mtrx)/Big;

    % Now let's look at it in several ways

    close all

    subplot(2,2,1)

    contour(Mtrx)

    subplot(2,2,2)

    pcolor(Mtrx)

    subplot(2,2,3)

    surf(Mtrx)

    subplot(2,2,4)

    image(Mtrx)

    The RNSR is:l The standard definition of a m x n Matrix A is :

    A11 A12 A13 A14 . . . A1nA21 A22 A23 A24 . . . A2n: :Am1 Am2 Am3 Mm4 . . . Amn

    l But!

    Which way round are graphics and images?Is it A(x,y) or A(y,x) or even A(-y,x)?

    l The RNSR isA(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 There are several commands for showing thecontents of a Matrix Z as Z = f(v,h)

    l As a contour map:contour(Z) orcontour3(Z) (lots of variations)

    l As a pseudocolour mappcolor(Z)

    l As surface in perspectivesurf (Z) orsurfc(Z) orsurf1(Z)

    l As mesh in perspective mesh, meshc, mesh1

    l As an image image(Z). Remember this shows theMatrix Upside Down

    l As always - use help to find out more

  • 8/4/2019 Matlab Notes 2005

    21/23Software and Computing I Page

    The Mandelbrot Set

    Z n = +Z Cn 12

    Where Z and C are complex

    For what values of C does it converge?

    Consider this iteration:

    This can only be solved by

    trying it on a computer

    Explore the Space of C

    % D M Monro1 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,

    % Initialize everything

    Inside = ones(MeshSize);

    % Draw the MandelbrotSet

    close all

    % Run C from MinC+i*MinC to MaxC+i*MaxC

    for RealMesh= 1:MeshSize

    RealC = MinC+ DeltaC*(RealMesh-1)

    for ImagMesh=1:MeshSizeImagC= MinC+ DeltaC*(ImagMesh-1);

    Z=0;

    C=RealC + i*ImagC;

    % Now the Iteration

    for Iters= 1:MaxIters

    Z = Z^2 + C;

    end

    Inside(ImagMesh,RealMesh) = abs(Z) f, where f is a fence. If |z|has jumped the fence, colour it white. If z has not jumped the fence, colour itblack. 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 ofiterations it takes to jump the fence. W ow!

    6.1.4 Find out how to solve the equation z^3 = 1 by Newtons method. Colour thespace of starting values of z according to which of the three possible solutionsthe iteration approaches. The answer is:

    Yikes!

    l6.2 Using Matrices - Equation

    Solving

    lMatrix Arithmetic

    lSolving Equations

    Matrix Arithmeticl 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=pA*B is legal if n=p, result is mxqA^B is special - see referencesA/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.^BAlso many functions e.g. sqrt(A) conj(A)

    l Transposition A is an nxm Matrix such thatA(m,n) = conj(A(n,m))

    Solving Equationsl 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 ofthe same size (r,1)

    l If A is rxr and det(A) ~= small, thenthe solution is (of course)x = A-1 y = inv(A)*y in MATLAB

    l If A is mxr, MATLAB will give the best fitsolution for any value of m, I.e. a leastsquares fit:x = A\Y this is cool!

  • 8/4/2019 Matlab Notes 2005

    22/23Software and Computing I Page

    l6.3 Mask and Vector Calculations

    lMatrix Comparisons

    lMatrix Logic

    lMatrix Masking

    lMore Fractal stuff

    lExercise - From a Previous Exam

    Matrix Comparisons

    l MATLAB can do comparisons of matricesMatrix1 compare operation value(or value logical operation Matrix1)

    The result is a matrix of 0 (False) or 1 (True) valuesl The comparisons available are:

    < less than greater than >= greater or equal== exactly equal ~= not exactly equal

    l These operations also have a precedence, amongthemselves and with the Arithmetic Operators.

    l If the value is a matrix, both must be the same size

    l The result is a matrix of the same size as Matrix1with 1s where the result is true and 0s where it is not

    Matrix Logic

    l 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

    l The logical operations available are:

    & AND | OR ~ NOT xor exclusive OR

    l These operations also have a precedence, amongthemselves and with the Arithmetic Operators.

    l If the value is a matrix, both must be the same size

    l The result is a matrix of the same size as Matrix1with 1s where the result is true and 0s where it is not

    Matrix Maskingl Tricky: A Mask can select points in an array:

    % Demonstrate a Mask% Construct some dataA = ones(10);for col = 1:10

    A(:,col) = A(:,col)*col;endAC = ones(10);% Make a MaskMask = A>5C(Mask) = A(Mask)

    l Size of Matrices and Masks must all be the same

    Remember Mandelbrot

    Where Z and C are complex

    For what values of C does it converge?

    Consider this iteration:

    This can only be solved by

    trying it on a computer

    Z n = +Z Cn 12

    Mask and Vector Mandelbrot

    % Draw the MandelbrotSet

    % D M Monro1 December 1998

    % Define the Space of C

    MeshSize=20,MinC = -1, MaxC= 1,

    DeltaC = (MaxC-MinC)/(MeshSize-1);

    % Controls over the IterationMaxIters=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

    end

    % Now the Iteration

    for Iters= 1:MaxIters

    % Iterate wherever Z is inside the Fence

    Z(Inside) = Z(Inside).^2 + C(Inside);

    Inside = abs(Z)

  • 8/4/2019 Matlab Notes 2005

    23/23

    ExerciselFrom 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 isrepresented 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

    (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 bythe 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 inputparameters 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]

    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]