mat lab plotting 1fvcsc a

Upload: sujit-dunga

Post on 03-Jun-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    1/14

    Matlab (Part 1: 2-Dimensional Plotting):

    Due Sunday, April 5 at midnight.

    Note: You can choose to work with a partner or you can choose not to. Your choice. You know the

    rules by now.

    First, a cool surface plot:

    Type in the following:

    >>t = 0:0.01:1

    This puts a list of numbers from 0 to 1 by intervals of .01 into t

    (Note: if you put a semicolon at the end of the line, it doesnt print out all the values. If you dont place

    the semicolon at the end of the line, it does. Try recreating t (type in the same exact thing), only thistime put a semicolon at the end of the line. See?

    >>y = 2*pi*t

    This takes every number in t and multiplies it by 2*pi (pi is built into matlab, so we dont have to import it

    in a library)

    >>x = sin(y)

    This takes every number in y and takes the sin of it and puts that list of numbers into x

    >>w = x*x

    this multiplies the inverse of x by x

    >>surf(w)

    This creates a surface plot of w (someone look up surface plot and tell me what it is, but it looks really

    cool!)

    To turn in:Nothing this was just for fun (for now).

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    2/14

    Introduction to 2-D Plotting:

    Plotting Introduction:

    The basic 2-D plot command is: plot (x,y) where xis a vector (an array, or a list), and yis a vector (an array, or list).

    Both vectors musthave the same number of elements.

    The plot command creates a single curve with the xvalues on the abscissa (horizontal axis) and the y

    values on the ordinate (vertical axis).

    The curve is made from segments of lines that connect the points that are defined by the xand y

    coordinates of the elements in the two vectors.

    Try it: Create two arrays (vectors) of numbers (note the lack of commas between elements in your array, which is

    different from python):

    >> x=[1 2 3 5 7 7.5 8 10];

    >> y=[2 6.5 7 7 5.5 4 6 8];

    Then plot the two vectors:

    >> plot(x,y)

    Well, that was exciting. Now youve got a line plotted. I think we need to add a few things though to make it more

    interesting. We can start with line specifiers. Line specifiers specify information about how the line will appear.

    8 10 12 14 16 18 20 22 240

    200

    400

    600

    800

    1000

    1200

    DISTANCE (cm)

    INTENSITY(

    lux)

    Light Intensity as a Function of Distance

    Comparison between theory and experiment.

    TheoryExperiment

    Plot title

    y axislabel

    x axislabel

    Text

    Tick-mark label

    EXAMPLE OF A 2-D PLOT

    Data symbol

    Legend

    Tick-mark

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    3/14

    So, for instance: plot(x, y, - r +) will plot the above line with a solid line (-), the line will be red (r) and the markers

    on the line will be + (+). Below is a partial chart of possible line specifiers (awfully similar to pythons).

    Line Style Specifier Line Color Specifier Marker Type Specifier

    Solid

    Dotted

    DashedDash-dot

    -

    :

    ---.

    Red

    Green

    BlueCyan

    Magenta

    Yellow

    Black

    white

    r

    g

    bc

    m

    y

    k

    w

    Plus sign

    Circle

    AsteriskPoint

    Square

    diamond

    +

    o

    *.

    s

    d

    Try the following (and feel free to try any other combination youd like:

    >>plot(x,y)

    >> plot(x,y,r)

    >> plot(x,y,--y)

    >> plot(x,y,*)

    >> plot(x,y,g:d)

    Okay, thats a nice start. But what if we have something like this that we want to plot:

    First, lets create our x coordinate:

    >>year = [1988:1:1994]

    This creates an array with the first value being 1988, and including as a separate entry in our array every value

    between 1988 and 1994 in increments of 1. In other words, our new array called year will hold [1988 1989 1990

    1991 1992 1993 1994] Type >>year at the prompt to confirm.

    Then create our y-coordinate:

    >> sales=[127,130,136,145,158,178,211]

    Now lets plot it:

    >>plot(year,sales,- - r*)

    You can also set the minimum and maximum limits for the x and y axis using axis([xmin xmax ymin ymax]):

    YearSales (M)

    198 1989 199 199 199 199 19912 13 136 14 15 178 211

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    4/14

    >>axis([1988 1994 120 220])

    Okay, so far so good. However, this clearly represents the house sales in one neighborhood. What if we wanted

    more than one line on our plot? Lets say we had a chart that looked something like this:

    Year 1988 1989 1990 1991 1992 1993 1994

    Sales(B) 137 130 172 204 178 158 141

    We can do this two ways: One is kind of moot at this point considering weve already created our plot, but in the

    future if we know we want to plot more than one line simultaneously, we can do it using:

    plot(x,y,u,v,t,h)

    This plots 3 graphs simultaneously: yversus x, vversus u, and hversus t. By default, MATLAB makes the curves in

    different colors.The curves can have a specific style by adding specifiers after each pair, for example:

    plot(x,y,-b,u,v,r,t,h,g:)

    In our case, however, weve already created our plot. We dont want to start over. Instead, we can add another

    line to our plot using the hold on/hold offcommands. What hold ondoes is hold the current plot and all axis

    properties so that subsequent plot commands add to the existing plot. Hold offreturns to the default mode

    whereby plot commands erase the previous plots and reset all axis properties before drawing new plots.

    So lets try this method. Notice that in this case, the y array is the same as it was previously for the first line on the

    graph. So we dont need to create a new array for the years. However, we do need to create a new array for the

    new sales amounts. Lets do that first:

    >> sales2 = [137,130,172,204,178,158,141]

    Now lets place the new plot line on our existing plot:

    >>hold on

    >>plot(year,sales2,: cs)

    >>hold off

    Cool! We added another line to our plot!

    Okay, our plot is looking pretty colorful. But what now? We probably want to save this, and maybe we want to

    save it in a way we can use it in, say, a MS Word document. We can do this using the print option: print

    Print options include:

    -dtiffprints current figure to .tiff format (into filename.tiff)

    -depseps file

    -depsccolor eps file

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    5/14

    -djpegjpeg image

    -dpngpng image

    So, for instance, if we wanted to save the current plot as a png image, wed do: print dpng Ourplot.png.

    Well save ours as a jpeg file.

    >> printdjpeg Houseplot.jpg

    Now open up Houseplot.jpg(outside of Matlab) to make sure it looks like your Matlab plot.

    Save this to turn in later.

    Plotting equations:Well plot the equation, y=3x

    326x + 10 and its first and second derivatives, for -2 x=[-2:0.01:4]

    (x now holds a vector from -2 to 4 by increments of .01)

    Then well make the vector y with the equation value at each x value (Note: the .^means to the power of)

    >>y=3*x^3-26*x+6

    (3 multiplied by x to the 3rd

    power, minus 26 multiplied by x, plus 6)

    (Note, when you multiply by x, youre creating an array in which you multiply by each value in the x array. So really

    what were saying aboveis:

    y[0] = 3*x[0].^326*x[0] + 6,

    y[1] = 3*x[1].^326*x[1] + 6,

    y[2] = 3*x[2].^326*x[2] + 6,

    for each value in x)

    Now well create a vector yd with the values of the first derivative:

    >>yd = 9*x.^2-26

    (9 multiplied by x squared, minus 26)

    Now well create a vector ydd with the values of the second derivative:

    >>ydd = 18*x

    (In case you couldnt figure this one out, its just 18 multiplied by each x value)

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    6/14

    And now well plot 3 lines, the function, the first derivative, and the second derivative:

    >>plot(x,y,-b,x,yd,r,x,ydd,:k)

    You should have a plot with a blue, a red, and a black line. Add a title, a legend, and an x and y label. Then save

    this to a jpg file as derivativeplot.jpg.

    Save this to turn in later.

    Part 3: Plotting a functionWhat if you wanted to plot a function? You can! Matlab wouldnt be matlab if it didnt let you plot a function! Say

    we wanted to plot:

    y = 3.5-0.5x

    cos(6x) for -2x = [-2:0.01:4]

    Then we calculate a value of y for each value in x:

    >>y=3.5.^(-0.5*x).*cos(6*x)

    And then wed plot it (adding the line specifiers of your choice):

    >>plot(x,y)

    Add a title, a legend, and an x and y label. Then save this to a jpg file as plottingcos.jpg.

    Save this to turn in.

    A simple line plot (with labels)

    Here are the MATLAB commands to create a simple plot of y = sin(3*pi*x) from 0 to 2*pi.

    >> x = 0:pi/30:2*pi;

    x is a vector (list) holding values from 0 to (and including) 2*pi, in increments of pi/30

    >> y = sin(3*x);

    y is a vector (list) holding the sin of 3* each value in x

    >> plot(x,y)

    >> xlabel('x (radians)');

    label the x-axis

    >> ylabel('sine function');

    label the y-axis

    >> title('sin(3*x)');

    put a title on the plot

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    7/14

    The effect of the labeling commands, xlabel, ylabel, and title are indicated by the text and red arrows in

    the figure.

    To turn in:Save the file using the File-> Save As->plot1.jpg(make sure you scroll down to jpeg under

    save as file type)

    A simple symbol plot

    This example shows you how to plot data with symbols. This type of plot is appropriate, for example,

    when connecting data points with straight lines would give the misleading impression that the function

    being plotted is continuous between the sampled data points.

    Here are the MATLAB commands to create a symbol plot with the data generated by adding noise to a

    known function.

    >> x = 0:0.01:2;

    x holds a vector (a list) from 0 to 2 by increments of 0.01

    >> noise = 0.02*randn(size(x));this returns a list of random numbers that is the same length as x (each number is multiplied by .02)

    this is a noise vector (list)

    >> y = 5*x.*exp(-3*x) + noise;

    y now holds a list of numbers, the exponent of x, with noise added to each number. So, for each value

    of x, we take the exp(-3*x) * 5, and then add the noise value from the noise list.

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    8/14

    >> plot(x,y,'o');

    >> xlabel('x (arbitrary units)');

    add axis labels and plot title

    >> ylabel('y (arbitrary units)');

    >> title('Plot of y = 5*x*exp(-3*x) + noise');

    Note that the ``.*'' operator is necessary when multiplying the vector x by the vector exp(-3*x). You

    should get the following plot:

    To turn in:Save the file using the File-> Save As->plot2.jpg

    An example of putting multiple curves on a plot

    You saw this a bit in the previous lab, but heres the MATLAB commands for creating a symbol plot with

    the data generated by adding noise to a known function. The original function is drawn with a solid line

    and the function plus noise is plotted with open circles.

    >> x = 0:0.01:2;

    >> y = 5*x.*exp(-3*x);

    >> yn = y + 0.02*randn(size(x));

    yn now holds a noisy version of y

    >> plot(x,y,'-',x,yn,'ro');

    This plots both y and yn against x, so you can see the original function and the noisy function. Notice

    that we put both x and y, followed by the symbol we want to use for that line, and then x and yn and the

    color (red) followed by the symbol (o) we want to use for that plot. See the next page for the resulting

    plot.

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    9/14

    >> xlabel('x (arbitrary units)');

    add axis labels and plot title

    >> ylabel('y (arbitrary units)');

    >> title('Plot of y = 5*x*exp(-3*x) + noise');

    >> legend('true y','noisy y');

    This adds the legend (in the top right corner, below). The first line plotted (the yellow, smooth line) gets

    the label true y, and the second line plotted (the red line represented by the o symbol) gets the label

    noisy y.

    Note that the ``.*'' operator is necessary when multiplying the vectorxby the vector exp(-3*x).

    To turn in:Save the file using the File-> Save As->plot3.jpg

    Peaks

    The peaks function is a function of two variables which produces example data that are useful for

    demonstrating certain graphing functions (The data are created by scaling and translating Gaussian

    distributions.) Calling peaks with a single argument n will create an nxn matrix. We can use the peaks

    function to demonstrate the power of using a matrix argument in the plot function. Try:

    >>plot(peaks(100)

    >>title(Plot of Peaks Function)>>text(80,8.5,Peak value)

    >>text(22,-7,Lowest peak value)

    This adds text inside the plot at x = 80, y = 8.5. It then adds text at x=22, and y = -7.

    (Cmon, isnt that cool?) What this plot plotted was a 100x100 matrix. So there are 100 separate lines

    on the graph. Now, if you have a matrix (in python this is, essentially, a list of lists), you can plot it by

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    10/14

    inputting the matrix. (In python, what youre seeing is each list plotted separately simply by entering

    the list of lists into the plot command).

    To turn in:Save the file using the File-> Save As->plot4.jpg

    SubplotsThe subplot command allows you to subdivide the graphing window (the figure window) into a grid of m

    rows and n columns, and place a separate plot into each of the squares in the grid .

    >> h = 1/16;

    >> x = 0:h:1;

    >> y = 0*x;

    Makes a list of 0s the same length as x

    >> y(1) = 1;

    >> for i=2:max(size(y)),

    y(i) = y(i-1) + h/y(i-1);end

    Note that indents dont matter in matlab. Its the word end that tells matlab where the for loop ends.

    Weirdness that must be mentioned: i=2:max(size(y)) This gives us the length of y, so were going from 2

    up through the length of y. I couldve used length(y) here. I COULD NOTve used size(y). Because in

    matlab everything is a matrix, so a list, or vector, or array, is a 1 by x matrix. So if I type in size(y), I

    should get 1 17 (or however elements are in y). By using max(size(y)), Im saying max (1,17), or 17. I

    was making your life interesting.

    >> true = sqrt(2*x+1)

    Sets the vector true to hold the square root (function built into matlab) of 2* the value in x + 1

    >> plot(x,y,'go',x,true)

    look at your figure window

    >> plot(x,abs(true-y),'mx')

    Okay, so weve plotted them. But we want them to be plotted side by side so we compare them:

    >> subplot(1,2,1);

    Im saying create a subplot grid of 1 by 2, and plot in the first square in the grid.

    >> plot(x,y,'go',x,true)

    >> subplot(1,2,2);Im saying in the plot grid of 1 by 2, and plot in the second square in the grid.

    >> plot(x,abs(true-y),'mx')

    >> title ('Errors for h=1/32')

    Adding a title, xlabel, and ylabel for the second plot

    >> xlabel('x');

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    11/14

    >> ylabel('|Error|');

    >> subplot(1,2,1);

    Switching back to the first plot to add labels

    >> xlabel('x');

    >> ylabel('|Error|')>> title('Errors for h=1/16')

    The figure you should get is:

    To turn in:Save the file using the File-> Save As->plot5.jpg

    Polar Plots:

    Matlab provides plotting capabilities with polor coordinates. polar(theta, r) generates a polar lot of

    angle theta (in radians) and a radial distance r.

    Try:

    >> theta = 0:0.2:5*pi

    >> rho = theta.^2;

    >> polar(theta, rho, '*')

    >> subplot(1,1,1)

    This sets the figure window back to being a 1x1 grid, with you plotting in the first square in the grid.

    >> polar(theta, rho, '*')

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    12/14

    Your plot should look like this:

    To turn in:Save the file using the File-> Save As->plot6.jpg

    Bar Graphs and Pie Charts

    Bar graphs, histograms, and pie charts are popular for reporting data. Here is a table of some of the

    commonly used Matlab functions for creating bar graphs and pie charts:

    bar(x) When x is a vector (list), bar generates a vertical bar graph. When x is a 2-dimensional

    matrix, bar groups the data by row

    barh(x) When x is a vector (list), bar generates a horizontal bar graph. When x is a 2-

    dimensional matrix, bar groups the data by row

    bar3(x) Generates a 3-dimensional bar chart

    bar3h(x) Generates a 3-dimensional horizontal bar chart

    pie(x) Generates a pie chart. Each element in the matrix is represented as a slice of the pie.

    pie3(x) Generates a 3-dimensional pie chart. Each element in the matrix is represented as a

    slice of the pie.

    hist(x) Generates a histogram.

    Lets try creating some of these plottypes. Well be using the subplot function to put them all in one

    figure window:

    >> x = [1,2,5,4,8];

    >> y = [x;1:5]

    This creates a matrix (list of lists) of the x list and a list with values from 1 through 5.

    >> subplot(2,2,1)

    >> bar(x),title('A bar graph of vector x')

    >> subplot(2,2,2)

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    13/14

    >> bar(y),title('A bar graph of matrix y')

    >> subplot(2,2,3)

    >> bar3(y),title('A 3-dimensional bar graph')

    >> subplot(2,2,4)

    >> pie(x),title('A pie chart of x')

    This stuff is just too cool! Heres what your results shouldlook like:

    To turn in:Save the file using the File-> Save As->plot7.jpg

    A histogram is a special type of graph that is particularly useful for the statistical analysis of data. A

    histogram is a plot showing the distribution of a set of values. In Matlab, the histogram computes the

    number of values falling into 10 bins (categories) that are equally spaced between the minimum and the

    maximum values. For example, if we define a matrix x as the set of grades from the Introduction to

    Computer Science final, the scores could be represented in a histogram, as shown below, and generated

    using the following code:

    >> subplot(1,1,1)

    >> x = [99,77,88,66,72,51,95,78,71,69,47,82,91,73,76,83,75,93,82,31];

    >>hist(x)

    This will give you a histogram with 10 bins. If you want a finer grade, youd enter the number of bins

    you want. For example:

    >>hist(x,25)will create a histogram with 25 bins. The figure will look like this:

  • 8/12/2019 Mat Lab Plotting 1fvcsc A

    14/14

    To turn in:Save the file using the File-> Save As->plot8.jpg

    Note: if you ever want help with plotting, you can just type

    >>help plot

    into the command window in matlab and youll get helpful information on plotting.

    End of 2-Dimensional Plotting Tutorial

    (Note: You can do all of this in python as well using the matplotlib and possibly scipy and numpy

    libraries)

    To turn in:

    1. Houseplot.jpg

    2. derivativeplot.jpg

    3. plottingcos.jpg

    4. plot1.jpg

    5. plot2.jpg

    6. plot3.jpg

    7. plot4.jpg

    8. plot5.jpg

    9. plot6.jpg

    10.plot7.jpg

    11.plot8.jpg