matlab lab2

download matlab lab2

of 10

Transcript of matlab lab2

  • 8/10/2019 matlab lab2

    1/10

    1

    060612/Thomas Munther

    Halmstad University

    School of Information Science, Computer and Electrical Engineering

    Laboratory 1Length about 2 hours with supervision.

    Even if if you completed the whole Lab-PM during these 2 hours you should try to

    find the time to work through this Lab-PM thoroughly afterward.

    The last page contains hand-in assignments. You should try to solve them within a

    week to be able to follow the pace in the course.

    Everything that follows after >> is written in the Matlab Command Window and

    indicates what you as a user should write. The % is intended as a comment to that

    specific command.

    Start Matlab by a double click on the Matlab icon or else by searching for it underprogram !Now, there should be a large window containing several smaller. These could for

    instance be: Command Window, Command History and Workspace.

    This will of course depend on what version you are currently working in.This is the desktop of Matlab.

    Command Window: Here you can write your own command lines and access yourown files ( m-files), but normally you can also see the output from the calculations in this

    window.

    Command History: All command lines are saved here and can be seen in the window, butthe same can be achieved by using the arrow button (up). The past command lines can the

    be seen in the command window.

    Workspace: The variables that have been used or created during the execution will be

    shown in this window. Here you can see value, bytes and class.When you double click on the variables, the elements of the variables become visible.

    These three windows should be the default when you start Matlab.This can of course be altered by Desktop->Desktop Layout or you can construct your

    own layout and save it.

    Current Directory: The directory where you save your m-files or where you store them.

    Matlab prefers that you store your m-files in the directory work, but you can of course

    put them anywhere you want.If you choose to put them in any other directory, you should give the path to the directory

    by File-> Set Path or select current directory.

  • 8/10/2019 matlab lab2

    2/10

    2

    During the course you will need to use the Help Browser in Matlab in order to find out

    how a certain command works. In the Help Browser you can also find related commandlines, examples, description, or help with the syntax.

    Try to use help browser by selecting: Help-> Help Browser

    This window is divided into two subwindows. The left window is named Help Navigator.

    Under Search write Sinand press enter ! To see the result look above !

    Exercise 1:By using the help browser you can find out how the sine function works .

    Make a plot of a sine function. The interval should be -10 to +10 radians.

    Each command line that is written in the command window is followed by enter.

    Note how this is done in the help browser.Now x becomes a variable in Workspace. Double click on x to see which elements are

    within the variable. If you follow the example x will have 2001 elements. In this case x isa one-dimensional vector. The first command line gives x and the second command line

    plots the sine function versus the x values in a figure window.

    The sine function is only evaluated for those x-values that are presented.

    Exercise 2:Now repeat the above example for a different function using the logarithmic

    ( base 10) function instead.

    Plot the function for an interval x=0.1:0.01:10.It means that x goes from 0.1 to 10 with a resolution of 0.01 ( 0.1, 0.11, 0.12,

    0.13.......,10).Use the help browser and the left subwindow and index to search for a command thatgives a logarithm. Maybe you can guess the first letters in this command.

    The plot should look like Figure 1 below.

    Suitable check values are log(10) and log(1)to see if the plot is reasonable.

  • 8/10/2019 matlab lab2

    3/10

    3

    Figure 1

    Please note that x has changed its elements and size !

    Lets now illustrate how to create an m-file(macro) or if you prefer a small program.

    Assume that we have to make a number of command lines before we end up with a plotin a figure window. If we make an error in the command line then we have to repeat the

    command line sequence. A better way, should be to put the command line sequence in an

    m-file and just correct the bad command line there. Execute the m-file simply by writingthe name of the m-file in the command window and without the extension .m .

    In order to let Matlab find the m-file give the path or make the directory where you have

    stored the m-file to your current directory.

    Exercise 3: Open an edit window where we can write the command lines. Click on thewhite sheet in the menu under File or simply write edit in the command window.

    Alternatively

    File->New ->M-file. The following is written in the edit window:-------------------------------------------------------------------------------------------------------

    % M-file created 060118 by Thomas Munther.

    t=0:0.01:10; % t goes from 0 to 10 in steps of 0.01.

    y1=sin(t); % everything to the left of the equality sign is an assignment, y1 is% variable.

    plot(t,y1), grid % plots y1 versus t and puts a grid on the plot.

    hold % holds the figure window and allows several plots to be made in the

    % same figure.y2=sin(2*t); % variable y2 is introduced and calculated.

    plot(t,y2) % plots y2 versus t in the same figure window as above.title(Exercise 3) % puts a title in our plot.

    xlabel(tid) % gives a label to the x-axis.

    ylabel(y)

    legend('sin(t)','sin(2*t)') % puts a box with text for different plots.----------------------------------------------------------------------------------------------------

  • 8/10/2019 matlab lab2

    4/10

    4

    Everything that follows % on the same line is a comment and is disregarded.

    Also note the semicolon ! It prevents output from a command to be seen in the commandwindow. If the command is a calculation, it is still calculated, but it is not visible.

    Save the m-file as exercise3.m in directory work. Run the m-file by writing exercise3 in

    the command window followed by enter.The result should be the same that as in Figure 2.

    Figure 2

    Note that title, xlabel, ylabel and legend could have been performed in the figure

    window, in the menu under Insert. It looks a bit odd that both curves have the same linestyles. This could well be a problem if we did have a problem with trigonometric

    functions. We will try to solve this. Click on the arrow in the menu of the figure window.Then double click on any of the curves. Enter under Style->LineStyle and change to

    dotted line. You can also change the if you want(Line Color) .

    There is also a possibility to exclude or exchange values in the plot. Lets illustrate howthis is done.

    Double click on any curve and choose Data->YData->y1 and then Edit Data. Now all

    plotting values that are used for one of the sine curves are accessible. Change the values

    to 2 for all indexes from 10 to 20. Take a new look on the plot !!This is perhaps not normal procedure in dealing with data, but I am just showing the

    possibilities with different tools.

    Before we end this take a small look

    Enter View->Camera Toolbar and mark it !Now we get another tools menu in the figure window. By this it is possible with 3D, to

    rotate the plot, to make it move over the screen and much much more.Try it !

    By now you have constructed your first m-file. There are two sorts of m-files: command

    line and function m-files. Note that an m-file must not begin with a number.The name must not contain dots or space for nothing else than extension.

  • 8/10/2019 matlab lab2

    5/10

    5

    Exercise 3 was an example of a command line m-file. It only consisted of a number of

    command lines executed when the name of the m-file was written in the commandwindow. Sometimes you want to use one, several or no argument as input to an m-file.

    Such an m-file has the following structure:

    function output_argument=name(input_argument)

    Function means it is a function m-file.

    Exercise 4:

    Lets write a function file range.m that calculates the difference between the maximumand minimum value in a vector. The file should return a reply. Open a edit window!

    Create a function file like the one below.----------------------------------------------------------------------------------------------------

    % the m-file is created by Thomas Munther 060117

    % Exercise4, laboratory 1

    % The m-file calculates the difference between the largest and smallest element

    % in vector q.function r=range(q) % defines a function file range.m

    qmax=max(q); % finds the maximum value in the vector q.qmin=min(q); % finds the minimum -value in the vector q.

    r=qmax-qmin; % gives the value that should be returned.

    -------------------------------------------------------------------------------------------------------

    Save the m-file as range.m !

    Now please enter a vector q=[ 1 3 5 7 9] in the command window!

    Run the m-file by simply writing range(q) after the prompt in the command window.>> range(q) % do not forget to press enter.

    Exercise 5: In this example we will investigate numerical format of the output. Check

    the variable q from the previous exercise. You can find it in Workspace. Double click on

    it, then we will find ourselves in the Array Editor where we can manipulate elements in

    the variable q. In our case q is a vector. Right above q you can find Numeric formatand Size. Size tells us how large q is. In our case q is a 1X5 vector( 1row and 5 columns).

    Change it to a 1X4 vector !

    Switch the second element in the vector from 3 to 3.0001. Check if theres any change ifyou go from a number to a float in q !

    Exercise 6: In previous assignments we have used the concept vector. This is common

    knowledge for every who has read a course in linear algebra. We know that a vector is aspecial case of a matrix. A two-dimensional matrix is a rectangular table, where all the

    elements are ordered into rows and columns.

    A matrix of size mXn has m rows and n columns.In Matlab it could look like the following for a 2X3 matrix:

    A =

    1 2 3

    4 5 6

    It is written like:

  • 8/10/2019 matlab lab2

    6/10

  • 8/10/2019 matlab lab2

    7/10

    7

    Write clearin matlabs command window !

    Clears all variables in the Workspace.Do the following assignment:

    >> a=2, b=3

    What will be the result of a+b ?

    Of course it becomes 5, but please observe where the result is stored.In the temporary variable ans. This is always true if I make a calculation without any

    assignment to store the result in.

    Write! 34+2Now,anshas a new value.

    Check eps!

    Calculate 1/0+3 ! What is the answer ?

    Check the largest and smallest value represented in Matlab !

    Multiply the answers by 2. What happens ?

    Divide ansby ans. Matlab cant represent this with a number instead it answers NaN.

    Finally let us define complex numbers. Calculate the following:

    >> sqrt(-1) % squareroot of -1

    We can also write a complex variable as :>> z=2+3*i % complex variable z with real part 2 and an imaginary part 3.

    Try some of the built-in functions in matlab operating on complex numbers:

    complex(x,y) Gives a complex number with real- andimaginary-part.

    conj(z) Gives the conjugate of z.

    real(z) Gives real part of z.

    imag(z) Gives imaginary part of z.

    abs(z) Gives the absolute value of z.

    angle(z) Gives the phase angle of the complex

    number z.

    Observe ! There is nothing in Matlab that prevents you from making an assignmentwhere i=5 or whatever.

    Exercise 8:

    Matlab has five aritmethical operators. These are in order of priority:

    Priority 1 ^ Power

    Priority 2 * Multiplication

    / Rightdivision

    Priority 3 + Addition

    - Subtraction

  • 8/10/2019 matlab lab2

    8/10

  • 8/10/2019 matlab lab2

    9/10

    9

    >> load execution1 % collects all the variables stored in the mat-file execution1.mat

    Does it work ?

    We can also store everything that is displayed in the command window. Like the whole

    session both the command lines and the output from Matlab, id est the calculations.This can be done by:

    >> diary exercise9 % stores the whole session in a file exercise9(ascii-file).

    Everything that follows from now on in the command window will be stored in the ascii-

    file exercise9. Write just anything to get some response from Matlab into the commandwindow.

    diary off % turns of the storage of the session to the file exercise9.

    Find the file exercise9 and see if the content in the file is the same that were displayed inthe command window!

    ---------------------------------------------------------------------------------------------------------

    Finally a little table of different numeric display formats. Useful for one of the homeassignments and later on as well in the course.

    format short 4 decimal digits 0.3333

    format long 14 decimal digits 0.33333333333333

    format bank 2 decimal digits 0.33

    format rat fractional form 1/3format long e 14 decimal digits 3.33333333333333e-01

    format short e 4 decimal digits 3.3333e-01

  • 8/10/2019 matlab lab2

    10/10