Top Banner
A Brief Introduction to MATLAB Lyuba Alboul Centre for Automation and Robotics Research, MERI Department of Engineering and mathematics, ACES The purpose of these notes is to present basic functionalities of MATLAB. These notes also contain exercises, indicated with a box , to practice MATLAB and basic codes to illustrate some of its features. The codes will also be uploaded as separate files. Their content can be copied and used in your own programmes. 1. Getting started with MATLAB The name MATLAB derives from MAT RIX LAB ORATORY; is a computing language, which basic element is a matrix. MATLAB processes data in the form of arrays of numbers. MATLAB is a very powerful fourth generation programming language that integrates high-performance computation and visualisation into a very flexible programming environment. MATLAB has many built-in functions that can be used straightforwardly. This facilitate obtaining solutions to the user-defined problems. MATLAB has been installed on most of the computers on the City Campus. The version installed is MATLAB 2010b. On some of the older computers there is still an older version, MATLAB 2006b. The latest version has, of course, more capabilities, however most of computations will work well on MATLAB 2006b. Exercises:
15
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
  • A Brief Introduction to MATLAB

    Lyuba Alboul

    Centre for Automation and Robotics Research, MERI

    Department of Engineering and mathematics, ACES

    The purpose of these notes is to present basic functionalities of MATLAB. These notes also contain exercises, indicated with a box , to

    practice MATLAB and basic codes to illustrate some of its features. The codes will also be uploaded as separate files. Their content can be copied and used

    in your own programmes.

    1. Getting started with MATLAB

    The name MATLAB derives from MATRIX LABORATORY; is a computing language, which basic element is a matrix. MATLAB processes data in the

    form of arrays of numbers. MATLAB is a very powerful fourth generation programming language that integrates high-performance computation and

    visualisation into a very flexible programming environment. MATLAB has many built-in functions that can be used straightforwardly. This facilitate

    obtaining solutions to the user-defined problems.

    MATLAB has been installed on most of the computers on the City Campus. The version installed is MATLAB 2010b. On some of the older computers there

    is still an older version, MATLAB 2006b. The latest version has, of course, more capabilities, however most of computations will work well on MATLAB

    2006b.

    Exercises:

  • To begin MATLAB click the Start button in the left corner of the screen. In the search box, type MATLAB and then, if in the list of results, there are

    two versions of MATLAB, choose MATLAB 2010b . After several seconds MATLAB will be launched and its displays windows will appear, The default

    view of MATLAB 2010b is shown below.

    MATLAB User Interface

    Workspace Window. Contains variables defined whilst

    perform computations. Currently is empty

    Current Directory Window

    The middle window is the Command Window

    where you execute commands. Its environment is

    similar to a note pad.

    Command History Window records the commands

    execute in the command

  • Standard MATLAB windows

    Command window

    This is the main window, this is where enter variables, and type and execute commands. Commands can be re-executed by using up and down arrows on

    the keyboard.

    Workspace window.

    This window provides information about current variables. It allows to edit variables by opening array editor (double click), to load variables from files

    and to clear variables.

    Current Directory window

    This window shows current directory and MATLAB files in current folder. Before start typing commands in the Command Window, change directory to

    your home space, where you should create a new folder, e.g. 'MATLAB files' or 'Case study robotics'.

    History window

    Shows previously executed commands.

    Commands can be re-executed by double-clicking .

    Additional windows are Graphic windows, editing windows and help windows.

    In the Command Window

    After having created a new folder where you will keep your codes, and changing your current directory to this folder, type the following

    commands in the command window: 1) x = 10 (or any other value); 2) pi and press the enter key.

    Exercises:

  • 1) T he following expressions will be displayed in the Command Window

    >> x = 10

    x =

    10

    And you can notice that variable x has appeared in the Workspace.

    2) In this case the value of is displayed

    >> pi

    but the output is displayed in the following manner:

    ans =

    3.1416.

    'pi' is a predefined MATLAB function, specially to produce the value of .

    If you type in the Command Window the following expression:

  • x + pi

    You will get

    >> x + pi

    ans =

    13.1416

    >>

    'ans' is a default name for the output of computation, and the previous value 3.1416 is replaced by 13.1416 in the computer memory.

    Therefore, if you want to use some of computed quantities later on, name theses quantities explicitly! Please, bear in mind, that x =10 is an assignment

    statement, and not an algebraic identity. Also, MATLAB is case-sensitive, so variable x and X are two different variables!

    As you notice, only 4 decimal places are present in the value of .

    Try now 10 * pi.

    What happens?

    MATLAB performs all computations with double precision, however, the output of computation can be displayed in different formats.

    To view the current format, type

    get(0,'Format')

  • In the aforementioned examples the format used was short, which displays 4 decimal digits.

    To change the type of format type 'format type', for example format long, and type pi again

    >> pi

    ans =

    3.141592653589793

    To know about possible types of format type in the Command Window: help format.

    You can also use HELP window for various information related to MATLAB. You undock this window by clicking button DESKTOP in the MATLAB

    User Interface toolbar and then Help. The HELP window will be undocked.

    Now type y = 8; and type a semi-colon after assigning the value of 8 to variable y.

    What happened?

    Basic arithmetic operators in MATLAB

    ADD Subtract Multiply Divide Power + - * / or \ ^

    There are two division operators in MATLAB (/ - the right division and \ - the left division) . The results produced by these operators differ.

  • Execute the following; 3/12 and 3\12 and compare the outputs.

    Vectors and Arrays

    The basic data type in MATLAN is a multidimensional array of double precision floating point number. Any inputs is treated as an array.

    For example, type in the Command Window:

    >> size x

    ans =

    1 1

    The answer '1 1' means the following : the array x consists of one row and one column. However x is treated as a scalar in all computations. A vector is a

    one-dimensional array, which is a list of numbers arranged in a row or a column.

    For example, if we want to indicate the position of point A with coordinates 3,4, 5 in

    space. The position of A can be expressed in terms of a position vector. as rA = 3i + 4j +5k

    X

    Z

    Y

    A(3,4,5)

  • Determine the unit vector uA of the vector rA by writing a MATLAB command.

    Creating a vector:

    1. variable_name = [data], e.g. B = [1 6 8 9 0]; The vector B is created by typing its element inside the square brackets []. with or without

    comma (,). B1 = [1, 6, 8, 9, 0] is the vector identical to the vector B.

    2. variable_name = [m:s:n] , e.g. C = [0:3:360]. The vector B is a vector with constant spacing between its element. To find the number of

    elements in C, type 'size(C)' in the Command Window.

    3. t= linspace(X1,Xn,n). This commnad will create a vector with X1 as the first element, Xn - as the last element, and with the total number of

    element equal to n. e.g. D = linspace(0, 100, 3).

    4. Try the following , type e = 4, h=8, and

    Weird = [e, cos(pi/3), sqrt(h/e), 10]

    Creating a multi-dimensional array (matrix)

    A multi-dimensional arrays of numbers is created as follows

    variable_name = [1st row elements; 2nd row elements, ..., last row elements].

    For example, MatA = [1 2 5 6; 30 1 9 0; 8 6 2 1].

    Element-by-element Operations with arrays (operations that are performed on each element of arrays(s)).

    For example, given two vectors a = [ a1 a2 a3] and b = [ b1 b2 b3]

    Element -by-element addition and subtraction of two vectors a and b is as follows:

    a + b and the elements of the resulting array are : [a1 +b1 a2 +b2 a3+b3]

    Exercises:

  • a - b = [a1 -b1 a2 - b2 a3-b3].

    However element-by-element multiplication, division and exponentiation are performed by typing a period in front of the arithmetic operator:

    a .*b = [a1b1 a2b2 a3b3]

    a ./b = [a1 ./b1 a2 ./b2 a3./b3]

    a .^b = [(a1 )b1

    (a2) b2

    (a3)b3

    ]

    Element-by-element operations can be done with the arrays of the same size only.

    Perform the element-by-elements operations with vectors a = [2 4 5] and b = [1 5 6].

    Elementary built-in functions in MATLAB .

    MATLAB has many built-in functions to perform a number of common computations. For example, sqrt(x) Computes the square root of x.

    To get a list of all these functions type in the Command Window help elfun.

    Exercises:

  • SCRIPTS and FUNCTIONS in MATLAB

    Until now all the commands were typed in the Command Window and executed by pressing the Enter key. However, this is not convenient if we want to

    execute a series of commands that are related to each other ( a programme) to solve a particular problem. If a change is needed then all the commands

    previously executed have to entered and executed again.

    A better way of executing commands is to write them in a separate file (M-file, script of function file).

    There are two ways to create a M-file. One way is to type in the Command Window : edit name_file, then a small window will appear .

    If you answer Yes, the Editing window is open , where you can type your commands line by line. Please, bear in mind that the name of the file should be

    written without spaces!

    Scripts are sequential sequences of commands, assignments, comments and functions. A function file is described on the next page.

    Given a radius of a circle ( e.g. R = 5mm), write a script to find the length of its circumference and its area.

    To execute a script file type its name in the command window.

    Exercises:

  • A function y= f(x) in mathematics, where f is a mathematical expression, associates a unique value (output) of y to each argument x (input). many

    functions are predefined in MATLAB (see above), but whilst solving a problem, there are often certain functions need to be evaluated which are not built-in

    functions. If these functions need to be performed many times for different values of arguments , in such cases it is reasonable to create a user-defined

    function.

    A user -defined function is a MATLAB program which is created by the user and can be used as a built-in function. Functions control the way in which

    computations are done in MATLAB. In a schematic way a function file can be illustrated by the following diagram.

    Input data FUNCTION FILE Output data

    The first executable line in a function file MUST be the function definition line.

    It has the following form:

    function [output arguments] = function_name (unput arguments)

    The name of file should be the same as the function_name. The set of output arguments can be empty.

    For example,

    function [AREA, LENGTH] = circle_par(R)

    Write a function file to compute the area and the length of the circumference of a circle depending on R.

    The function file is executed by typing in the Command Window the function definition line without the word function, e.g. :

    [AREA, LENGTH] = circle_par(R)

    Instead of a letter 'R' a value should be given, e.g.

    [AREA, LENGTH] = circle_par(5).

    Exercises:

  • PLOTTING in 2D.

    The basic statement for drawing a graph in 2D is plot. The most common form of plot is plot(x,y), where x and y are vectors (one-

    dimensional arrays) of the same length.

    When the command plot is executed the resulting single curve will appear in the Figure Window. If the Figure Window has not yet been

    opened, it will open automatically.

    The resulting curve will be displayed with the x values on the horizontal axis (called abscissa) and the y values on the vertical axis (called

    ordinate). The curve is constructed of straight-line segments that connect the points with the coordinates (xi,y

    i) . The coordinates of the points

    are defined by the elements of vectors x and y accordingly (1 , is the number of elements in x and y).

    Create a plot of the function = (), where 2 2.

    Recall that as MATLAB basically deal with numerical values, we have to create an array (vector) of the values of x.

    x = [-2*pi:pi/40:+2*pi]; This generates an array of x values starting with x1 -2*pi with step (increment) pi/40 until it the last element xn that is

    less or equal to 2*pi. The smaller is the step; the smoother will be the resulting curve.

    plot(x,sin(x))

    The coordinates of each points are (xi,y

    i), where y

    i is equal to sin(x

    i), and i is the index (position) of the corresponding vector components.

    Write a small script that creates the above plot.

    The presentation of the graph can be improved. The plot command has additional arguments that can enhance appearance of the graph as well as increase its

    quality:

    plot (x, y, 'line specifiers', 'Property Name', 'Property Value')

    'Line specifiers' define the type and colour of the line and the markers .

    Exercises:

  • Line specifiers are optional and may consist of 3 symbols corresponding to line type, line colour and marker type (if markers are used).

    Symbols for each specifier belong to non-intersecting sets; therefore their order is not important.

    Examples:

    plot (x, y) the resulting curve is a blue solid line connecting the points with no markers (default option)

    plot(x, y, k) the resulting curve is a black solid line connecting points without markers

    plot(, x, y, -.r) the resulting curve is a red dash-dotted line connecting points without markers

    plot(, x, y, r-.) will produce the same result as above

    plot(, x, y, o) the points are marked with blue circles . There will be no line connecting points. If line specifiers are used, then the line style

    should be specified explicitly to produce a line.

    plot(, x, y, o) as above, only circles are red

    plot(, x, y, g-*) the resulting curve is a green solid line and points are indicated with * (asterisks)

    To find more about line specifiers go to the MATLAB HELP, Index, and type LineSpec.

    Bear in mind, that if use line specifiers, the curve and the markers will be of the same colour.

    In order to change the colour of the marker you need to use the properties.

    Properties and their values specify the line width, a marker size, its edge and fill colours.

    Below a sample of a script file is given that produces a plot for the = (), where 2 2.

    You can copy the content of this code in your own script file. Line that start with the symbol '%' are comments and are not executed.

  • % a script to create the plot of the function y = sin(x) , % where -2*pi
  • Write a script and a function file to plot a circle with the given coordinates (x,y) of its centre and radius r. For example, (3.4) and radius 3.

    Exercises: