mathlab for plot

Upload: toshafl

Post on 08-Apr-2018

239 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Mathlab for Plot

    1/11

    Plotting and Graphics

    Matlab offers fairly decent scientific visualization and graphics capabilities. In the currentversion, Matlab features both 2-D and 3-D graphics options. Some basic plotting and

    graphic features are presented and discussed in this tutorial through a series ofexamples.

    Example 1:

    We wish to plot the function:

    for the range oftfrom 0 to 5 with an increment of .1.

    In Matlab Command window, enter the following lines:

    Please note that the array representing the function ymust have the same dimension asthat of tarray. Array division "./" and array exponential ".^" are used to create the y

    array as a function of t.Note that Matlab will treat all entries after the "%" sign ascomment line. The command "gtext" is used to insert a user-defined text string at achosen cursor position on the graph. The graphic window displaying the plot is shown

    below:>

    MENU

    >

    >

    MENU

    >

    >

    MENU

    >

    >

    MENU

    >

    >

    MENU

    >

    >

    MENU

    >

    >

    MENU

    >

    >

    MENU

    >

    >

    MENU

    >

    >

    MENU

    >

    >

    MENU

    >

    Page 1 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting

    15.05.2011http://edu.levitas.net/Tutorials/Matlab/plotting.html

  • 8/6/2019 Mathlab for Plot

    2/11

    ___________________

    Example 2:

    Two or more plots can be shown on the same graph as shown in this example. In this

    example, an additional function "y2" is to be shown with function y plotted in Example 1on the same graph. Note that the "legend" function is used to label the plots. The entriesin Matlab command windoware as follows:

    The resulting plot is shown below:

    Note that markers are used in the "plot" function in Example 2 for the purpose ofidentification. The table below lists all markers offered in Matlab.

    Page 2 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting

    15.05.2011http://edu.levitas.net/Tutorials/Matlab/plotting.html

  • 8/6/2019 Mathlab for Plot

    3/11

    ______________________

    Example 3:

    You may show multiple plot in an array format. This can be achieved with the "subplot"command. You may arrange multiple plot in any array you wish, e.g., a 2 x 2 plot array

    would yield two plots on the top row and two plots on the bottom row. The functionsused in Examples 1 and 2 above can be shown in an array format by the following

    inputs:

    which, will produce these graphs in one plot:

    _________________

    Example 4:

    Matlab offers some neat 3-D plotting functions such as plot3 and mesh. In this

    example, a 3-D plot using mesh command is illustrated. To generate a 3-D plot using

    Designatedcolour

    Used in "plot" commandDesignatedlinestyle

    Used in "plot" command

    yellow y point .

    red r circle o

    green g x-mark x

    blue b plus +

    black k star *

    white w solid - (minus sign)

    magenta m dotted :

    cyan c dashdotted -.

    dashed -- (two minus signs)

    Page 3 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting

    15.05.2011http://edu.levitas.net/Tutorials/Matlab/plotting.html

  • 8/6/2019 Mathlab for Plot

    4/11

    mesh command, you first need to establish the domains of the "x-" and "y-", in whichthe function is evaluated with the command meshgrid. In this example, function:y=3sin(y) * cos(x) is plotted in the x-domain between -pi and pi with an increment of

    pi/50. Note that meshgrid function is used to transform the domain for plotting usingthe mesh command. The following commands illustrate the use of aforementioned

    plotting functions.

    The resulting plot is shown below:

    __________________

    Example 5:

    A 3-D plot is shown in the following example, where two functions sin(4t) cos(4t) are

    visualized as parameter t increases from 0 to 5 at an increment of 0.01.

    Page 4 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting

    15.05.2011http://edu.levitas.net/Tutorials/Matlab/plotting.html

  • 8/6/2019 Mathlab for Plot

    5/11

    A different view can be achieved with the function view

    Example 6:

    Note: Some features mentioned in this example are available only in Matlab 7.

    In this example, we will curve fit a set of raw data using two different methods of regressionregression and linear-in-parameters regression.

    Polynomial regression is modeled by

    and linear-in-parameters regression is modeled by

    Assume we are given a raw data set obtained from an experiment presented in array format as follow

    time=[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15], measured in seconds.

    volts=[0 21.7 15.9 14.2 10.8 6.8 5.7 4.5 4.3 3.7 3.5 2.8 3.1 2.6 3.3 2.5]

    We will compute the unknown coefficients a_o, a_1, and a_2 and plot the fitted curves against the rathe two regression methods mentioned above.

    First, let's open a Matlab editor to create an M-file and name it curvefit. Make sure that the file idirectory that has been included in Matlab defined path.

    (1)

    (2)

    Page 5 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting

    15.05.2011http://edu.levitas.net/Tutorials/Matlab/plotting.html

  • 8/6/2019 Mathlab for Plot

    6/11

    To bring up the editor in Matlab 7, click on the New M-file icon as shown:

    You may also bring up the editor from File > New > M-File.

    In the editor window, select Enable Cell Mode from Cell menu.

    The curvefit.m file should contain the following lines:

    % Regression and curve fitting example%% Raw data sett = [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]';y = [0 21.7 15.9 14.2 10.8 6.8 5.7 4.5 4.3 3.7 3.5 2.8 3.1 2.6 3.3 2.5]';plot(t,y,'o r'),grid %plot raw data points

    %% Polynomial regression

    X = [ones(size(t)) t t.^2];

    a = X\y %solving for unknown coefficientsT = (0:.5:16)';Y = [ones(size(T)) T T.^2]*a;plot(T,Y,'-',t,y,'o'), grid ontitle('Polynomial Regression')xlabel('time, sec')ylabel('Magnitude, volts')

    %% Linear-in-parameters regression

    X = [ones(size(t)) exp(-t) t.*exp(-t)];a = X\yT = (0:.2:16)';Y = [ones(size(T)) exp(-T) T.*exp(-T)]*a;plot(T,Y,'-',t,y,'o'), grid ontitle('Linear-in-Paramenters Regression')

    xlabel('time, sec')ylabel('Magnitude, volts')

    Note that %% is used to signify a cell, where a group of commands is executed in step process. Thisnew features offered in Matlab 7. I will demonstrate this feature in the following steps.

    As you type in the lines (as shown in blue box above) with cell mode enabled, you will notice thbackground is on automatically. Each time you enter "%%", a new cell is created.

    Once you finish entering all the lines, save the file and move the cursor the the first cell. Then click onof the cell evaluation group (Evaluate cell icon) as shown below.

    A typical desktop environment with docked figure of plotted raw data (first cell evaluated) is shown be

    A plot of raw data should popup. To take adva

    docking feature in Matab 7, click on the dockingat the upper right corner of the figure window.

    Note that the you may "undock" the figure atclicking on the undock arrow icon.

    This docking feature is particularly useful whensee both Matlab's results in the Command win

    content of the figure in one compact group.

    Page 6 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting

    15.05.2011http://edu.levitas.net/Tutorials/Matlab/plotting.html

  • 8/6/2019 Mathlab for Plot

    7/11

    Next, click on the second cell icon (Evaluate cell and advance icon). You will notice

    the yellow highlighted group is now shifted down to the second cell. Matlab effectivelyevaluated the first cell again and make the cell below the next active cell. To evaluatethe second cell and make the third cell active, click on this icon again.

    A plot of polynomial regression is now obtained.

    The unknown coefficients of Eq. (1) as obtained from Matlab Command window are:

    a_o = 13.1395

    a_1= -1.0932a_2= 0.0213

    You can see that the polynomial approximation we used did not yield a very good curvefitting. We may try to increase the order of the polynomial or use a different

    approximation.

    In this example we'll try the linear-in-parameters regression as defined in the third cell.

    Click on the first icon (Evaluate Cell icon). This effectively evaluates the third cell

    Page 7 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting

    15.05.2011http://edu.levitas.net/Tutorials/Matlab/plotting.html

  • 8/6/2019 Mathlab for Plot

    8/11

    containing instructions for linear-in-parameters regression.

    The unknown coefficients of Eq. (2) as obtained from Matlab Command window are:

    a_o= 3.9215a_1= -4.1214a_2= 53.4127

    This approximation has been shown to be better than polynomial regression for the

    given set of raw data.

    Combined plot

    Sometime you may want to show all plots in one figure like one shown below.

    The plot above was generated from the existing M-file listed above with only a few minormodifications. The command hold on was added preceding to the first plot command (inthe first cell).

    CURVE FITTING TOOL

    The current version (R2009a) of MATLAB offers 'friendlier' GUI on plotting. The followingexample demonstrates the use of curve fitting tool available in this version.

    Example 7:

    In this example a set of data is imported from a spreadsheet program like OpenOffice

    Page 8 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting

    15.05.2011http://edu.levitas.net/Tutorials/Matlab/plotting.html

  • 8/6/2019 Mathlab for Plot

    9/11

    Calc. The original data is tabulated below:

    Simply highlight the cells with numeric values and do a copy-and-paste into Matlabworkspace variable named "travel" then type in the command "cftool" in Command

    Window as shown below.

    A Curve Fitting Tool window will pop up. Next you need to set up two seperate arrays

    from the variable 'travel', namelyxarray and yarray. Both ofnx1 dimension, where n isthe number of data points. In Command window, type the followings:

    >> x=travel(:,1);

    >> y=travel(:,2);

    Now, go back to Curve Fitting Tool window and clidk on DATA button.

    This brings up a new window prompting you to select the data set. Under Data Sets tab

    Time, sec Dist, m

    0 266

    3 195.57

    6 137.35

    9 88.88

    12 48.24

    15 13.97

    18 -15.11

    21 -39.93

    Page 9 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting

    15.05.2011http://edu.levitas.net/Tutorials/Matlab/plotting.html

  • 8/6/2019 Mathlab for Plot

    10/11

    and X DATA group (pull-down menu), select 'x'. Similarly select 'y' from Y DATA group.

    In Data set name box, enter: "Distance vs. Time", then click on Create Data Setbutton followed by CLOSE button. This results in a plot as shown below.

    Now, click on Fitting... button.

    In the Fitting window, click on New Fit button and select Quadratic polynomial type,followed by Apply button. Note that you may select other algorithm of fitting from the

    menu that is appropriate for your needs.

    The calculated function that would best fit the data are presented in the Results box as

    follows:

    Linear model Poly2:f(x) = p1*x^2 + p2*x + p3Coefficients (with 95% confidence bounds):

    p1 = 0.4123 (0.3498, 0.4748)p2 = -22.97 (-24.33, -21.6)

    p3 = 263.1 (256.9, 269.2)

    The numbers in the parantheses are the bounded values. Thus, the function

    representing the fitted curve is:

    y(x) = 0.4123x2 - 22.97x +263.1

    and the fitted curve is displayed in Curve Fitting Tool window.

    You may want to explore the Analysis button, from which many neat features are

    available to help you to study the behaviors of the data such as derivatives andintegration of the approximated function.

    The results obtained in fitting process can be saved to workspace simply by clicking on

    Page 10 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting

    15.05.2011http://edu.levitas.net/Tutorials/Matlab/plotting.html

  • 8/6/2019 Mathlab for Plot

    11/11

    Save to workspace button.

    FINDING ROOT OF A FUNCTION

    To identify the value on the x-axis that corresponds to the zero value of y (y is afunction ofx), you may use the command fzero in Command window. In the exampleabove, we can locate the root of the function with the following entries:

    >> f=@(x)0.4123*x.^2-22.97*x +263.1;

    >> xzero=fzero(f,15)

    Matlab will compute the root near with the value 'near' the zero-crossing. This yields thevalue ofxzero = 16.1160, which is exactly where the function becomes zero.

    Version 7 also offers quite a few new user-friendly plotting tools such as textannotations, data cursor, and legend insert tools, etc. Data cursor tool is useful when

    you wish to know the coordinates of a particular point on the plot.

    Data cursor can be activated from Tools > Data cursor menu or by clicking onicon then lefit-click on the desired location on the existing curve. You may delete the

    current data tip by simply selecting it then press the Delete key.

    Background colour can be changed from View > Property Editor.

    Have fun!

    ______________________________________

    T. Nguyen MMX. All rights reserved.

    Page 11 of 11MATLAB TUTORIAL - by T. Nguyen: Plotting