plotting in matlab - l-università ta'...
Post on 18-Aug-2020
1 Views
Preview:
TRANSCRIPT
PlotsFunctions and Plots
Special Plots
Plotting in MATLAB
Trevor Spiteritrevor.spiteri@um.edu.mt
http://staff.um.edu.mt/trevor.spiteri
Department of Communications and Computer EngineeringFaculty of Information and Communication Technology
University of Malta
29 February, 2008
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Outline
PlotsPlot BasicsThe axisMultiple PlotsInteracting with Plots
Functions and PlotsPlotting FunctionsFunction Discovery
Special PlotsDifferent Plots3-D Plots
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
Outline
PlotsPlot BasicsThe axisMultiple PlotsInteracting with Plots
Functions and PlotsPlotting FunctionsFunction Discovery
Special PlotsDifferent Plots3-D Plots
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
The elements of a plot
0 1 2 3 4 5 6 7 8 9 100
50
100
150
200
250
300
350
400
450
500Height of a Falling Object Versus Time
Time (s)
Hei
ght (
m)
ModelMeasurement
Plot titleLegend
Data symbol
Axis label
Grid
Tick markTick-mark label
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
The elements of a plot explained
Ï The scale is the range and spacing of the numbers.
Ï The most-used scale is the rectilinear scale, also known as thelinear scale.
Ï Another kind of scale is the logarithmic scale.
Ï Tick marks are placed on the axis to help visualize thenumbers.
Ï A function is always plotted as a line, with no data symbols.
Ï When plotting data, data symbols are used, except if they aretoo dense.
Ï When plotting more than one curve, they must bedistinguished.
Ï This distinction can be made using a legend or labels.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
A correct plot
Ï Each axis must be labelled with the name and its units.
Ï Each axis should have regularly spaced tick marks. Theseshould not be too sparse or too dense.
Ï When plotting data points, use a data symbol such as a circle.If there are many symbols, use a dot.
Ï When plotting points generated by using a function, datasymbols should not be used.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
Plotting x-y data
Ï To plot x data against y data, type: >> plot(x, y)Ï To change the line specification, type: >> plot(x, y, s)Ï s contains the line style specifier, the marker specifier, and/or
the colour specifier.
Ï For example, for a solid line, a plus data marker, and the redcolour, the specifier would be '- + r'
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
Line specification string syntax
Line styles Markers ColoursSolid line - Plus sign (+) + Red rDashed line -- Circle (◦) o Green gDotted line : Asterisk (∗) * Blue bDash-dot line -. Point (·) . Cyan c
Cross (×) x Magenta mSquare (ä) s Yellow yDiamond (♦) d Black kUpward triangle (4) ^ White wDownward triangle (O) vRight triangle (.) >Left triangle (/) <Five-pointed star pSix-pointed star h
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
Labels, titles, and grids
Ï The xlabel function sets the label for the x-axis.
Ï The ylabel function sets the label for the y-axis.
Ï The title function sets the plot title.
Ï The grid on command displays the grid.
Ï The grid off command hides the grid.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
The axis
Ï The axis function sets the axis of the plot.
Ï To make the plot a square, type: >> axis squareÏ To make the x-axis and y-axis have the same scale, type:
>> axis equalÏ To set the x-axis in the range x1–x2 and the y-axis in the range
y1–y2, type: >> axis([x1 x2 y1 y2])Ï To return to automatic axis, type: >> axis auto
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
Scales
Ï The most commonly-used scale is the rectilinear scale, alsoknown as the linear scale.
Ï The plot command uses the linear scale.
Ï The loglog command is the same as the plot command,except that logarithmic scales are used for both the x-axis andthe y-axis.
Ï The semilogx command is the same as the plot command,except that a logarithmic scale is used on the x-axis.
Ï The semilogy command is the same as the plot command,except that a logarithmic scale is used on the y-axis.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
More than one line on the same axis
Ï To plot more than one line on the same axis, one way is to type:>> plot(x1, y1, s1, x2, y2, s2, . . .)
Ï Another way is to use the hold command.>> plot(x1, y1, s1)>> hold on>> plot(x2, y2, s2). . .>> hold off
Ï If x and y are matrices, to plot the columns of y against thecolumns of x, type: >> plot(x, y)
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
The legendÏ The legend can be used to distinguish between different lines.Ï To display a legend, use the legend command.
>> legend(string1, string2, . . .)Ï The specified strings will be used as labels.Ï The default legend location is the top right corner.Ï To change the location of the legend:
>> legend(string1, . . ., 'location', specifier)Ï The specifier for a location inside the axis can be 'North',
'NorthEast', 'East', and so on.Ï The default location is 'NorthEast'.Ï The specifier for a location outside the axis can be
'NorthOutside', 'NorthEastOutside', and so on.Ï For MATLAB to choose a place automatically, the specifier can
be 'Best' or 'BestOutside'.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
Text labels
Ï Another way to distinguish between lines is to label them.
Ï To write labels, use the text command:>> text(x, y, 'string')
Ï The specified string will be placed at the given coordinates.
Ï To place a label using the mouse, use the gtext command:>> gtext('string')
Ï Then click on the figure for the label to be displayed.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
More than one figure
Ï You can have more than one figure window.
Ï The figure command creates a new figure window.
Ï The close command closes the current figure window.
Ï The close all command closes all the figure windows.
Ï To have more than one plot in the same figure window, use thesubplot command.>> subplot(m, n, p)
Ï The figure is split into an m by n matrix of panes.
Ï The p parameter specifies on which pane subsequentcommands will work.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
Saving and exporting figures
Ï To save a plot, use the saveas command:>> saveas(handle, filename)>> saveas(handle, filename, format)
Ï The handle refers to a particular figure.
Ï The gcf function returns the handle of the current figure.
Ï The data can be saved to different formats, e.g., 'pdf'.
Ï If the format is not included, it is deduced from the extensionof the filename.
Ï Some common formats are 'fig' for a MATLAB figure, 'bmp','jpg', and 'pdf'.
Ï To save the current figure as a MATLAB figure, type:>> saveas(gcf, 'filename.fig')
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plot BasicsThe axisMultiple PlotsInteracting with Plots
The plot user interface
Ï Apart from the command interface, plots can be manipulatedusing the user interface (UI).
Ï Editing labels is easy using the UI.
Ï The UI makes it possible to insert other items onto a plot,including rectangles, ellipses, text labels, and arrows.
Ï Colours, fonts, and styles can be changed using the UI.
Ï Figures can be saved and exported from the UI.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plotting FunctionsFunction Discovery
Outline
PlotsPlot BasicsThe axisMultiple PlotsInteracting with Plots
Functions and PlotsPlotting FunctionsFunction Discovery
Special PlotsDifferent Plots3-D Plots
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plotting FunctionsFunction Discovery
Plotting functions
Ï Suppose you want to plot the function:y = cos(tan(x))− tan(sin(x)) for x ∈ [1,2]
Ï This can be done using:>> x = 1 : 0.01 : 2;>> y = cos(tan(x)) - tan(sin(x));>> plot(x, y)
Ï A better way is to use the fplot command.>> fun = 'cos(tan(x)) - tan(sin(x))';>> fplot(fun, [1 2])
Ï fplot automatically chooses the point spacing.
Ï The function can be defined as a string, as above.
Ï The function parameter can also be a function handle. Forexample, to plot sin(x), type: >> fplot(@sin, [-pi pi])
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plotting FunctionsFunction Discovery
Plotting polynomials
Ï Suppose you want to plot the polynomial:y = x5 −25x3 +10x2 +70x−10 for x ∈ [−5,5]
Ï To do this, use the polyval function:>> p = [1 0 -25 10 70 -10];>> x = -5 : 0.01 : 5;>> y = polyval(p, x);>> plot(x, y)
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plotting FunctionsFunction Discovery
Discovering a functionÏ Function discovery is the process of finding a function that can
describe a set of data.Ï Some functions can be discovered by trying to draw the
function as a straight line.Ï To discover these function, try each of the scales; plot(x, y),
loglog(x, y), and so on.
Table : Functions that can be plotted as stright lines
Kind of function Form Straight-line plotLinear y(x) = mx+b plot(x, y)Power y(x) = bxm loglog(x, y)Exponential y(x) = bemx semilogy(x, y)Logarithmic y(x) = m ln(x)+b semilogx(x, y)
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plotting FunctionsFunction Discovery
Regression analysis
Ï Suppose we control x, an independent variable, and wemeasure y, a dependent variable.
Ï y is a random variable because of observational errors.
Ï The least squares method is commonly used to find the best-fitmodel.
Ï If we have k data points for a linear function y = mx+b, theleast square method minimizess the error J given by:
J =k∑
i=1(mxi +b−yi)
2
Ï The polyfit(x, y, n) function finds the coefficients of ann-degree polynomial that fits the data best in a least-squaressense.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plotting FunctionsFunction Discovery
Finding the coefficients of a linear function
Ï Once we get a straight line, we know the function type.
Ï Interpolating values on logarithmic scales is difficult.
Ï To find the coefficients b and m, we use the linear scale.
Ï The polyfit function helps us to find the coefficients.
Ï If we get a straight line using the plot command, we have alinear function.
Ï A linear function is of the form:y = mx+b
Ï To find the polynomial coefficients of a linear function, type:>> p = polyfit(x, y, 1)
Ï m is p(1) and b is p(2).
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plotting FunctionsFunction Discovery
Finding the coefficients of a power function
Ï If we get a straight line using the loglog command, we have apower function.
Ï A power function is of the form:y = bxm
Ï Taking logs:ln(y) = m ln(x)+ ln(b)
Ï This has the form of a first-degree polynomial.
Ï To find the coefficients, we type:>> p = polyfit(log(x), log(y), 1)
Ï m is p(1) and ln(b) is p(2), that is, b is exp(p(2)).
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plotting FunctionsFunction Discovery
Finding the coefficients of an exponential function
Ï If we get a straight line using the semilogy command, we havean exponential function.
Ï An exponential function is of the form:y = bemx
Ï Taking logs:ln(y) = mx+ ln(b)
Ï This has the form of a first-degree polynomial.
Ï To find the coefficients, we type:>> p = polyfit(x, log(y), 1)
Ï m is p(1) and ln(b) is p(2), that is, b is exp(p(2)).
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plotting FunctionsFunction Discovery
Finding the coefficients of a logarithmic function
Ï If we get a straight line using the semilogx command, we havea logarithmic function.
Ï A logarithmic function is of the form:y = m lnx+b
Ï This has the form of a first-degree polynomial.
Ï To find the coefficients, we type:>> p = polyfit(log(x), y, 1)
Ï m is p(1) and b is p(2).
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Plotting FunctionsFunction Discovery
Interpolation and extrapolation
Ï Once a function is discovered from the data, it can be used topredict conditions within the range of the data.
Ï This is called interpolation.
Ï The function can also be used to predict conditions that lieoutside the range of the data.
Ï This is called extrapolation.
Ï Extrapolation assumes that the mathematical model remainsthe same beyond the data range.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Different Plots3-D Plots
Outline
PlotsPlot BasicsThe axisMultiple PlotsInteracting with Plots
Functions and PlotsPlotting FunctionsFunction Discovery
Special PlotsDifferent Plots3-D Plots
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Different Plots3-D Plots
Plotting complex numbers
Ï The plot(x, y) command plots values of y against values ofx.
Ï The plot(y) command usually plots values of y against theirindices, that is, against
[1 2 3 . . .
].
Ï But when y contains complex values, plot(y) plots theimaginary parts against the real parts.
Ï This can also be written explicitly as:>> plot(real(y), imag(y))
Ï This is the only condition in which imaginary parts of numbersare not ignored by the plot command.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Different Plots3-D Plots
Plotting polar plots
Ï Polar plots are 2-D plots made using polar coordinates.
Ï Polar coordinates are of the form (θ,r).
Ï θ is the angular coordinate of a point in radians.
Ï r is the radial coordinate of a point.
Ï To plot values of θ and r, type: >> polar(theta, r)Ï To specify the line style, type: >> polar(theta, r, s)Ï You can convert polar coordinates to rectangular (Cartesian)
coordinates: >> [x, y] = pol2cart(theta, r)Ï You can also convert rectangular coordinates to polar
coordinates: >> [theta, r] = cart2pol(x, y)
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Different Plots3-D Plots
Other plotsÏ stem(x, y) plots the data as stems from the x-axis
terminating in a marker.Ï stairs(x, y) draws a stairstep graph through the specified
points.Ï bar(x, y) draws a bar graph of the specified values.Ï scatter(x, y, areas) draws markers at the specified
locations. The area of each marker can be specified.Ï plotyy(x1, y1, x2, y2) produces two y-axis labels. The
y-axis label on the left is used to plot y1 against x1, and they-axis label on the right to plot y2 against x2.
Ï plotyy(x1, y1, x2, y2, fun1, fun2) lets you specify theplotting functions. To plot y1 against x1 using plot and y2
against x2 using stem, type:>> plotyy(x1, y1, x2, y2, @plot, @stem).
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Different Plots3-D Plots
3-D line plots
Ï To plot a function that varies in x, y, and z, use the plot3command.
Ï Suppose we have a parametric function:
x = e−0.07t cos t
y = e−0.07t sin t
z = t
Ï To plot this function for t ∈ [0,10π]:>> t = 0 : 0.01 : 10*pi;>> x = exp(-0.07 * t) .* cos(t);>> y = exp(-0.07 * t) .* sin(t);>> z = t;>> plot3(x, y, z)
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Different Plots3-D Plots
Meshes and surface plots
Ï Suppose we have a function of two variables, z = cos(xy).
Ï We want to plot this function for x ∈ [−3,3] and y ∈ [0,6].
Ï To generate values of x and y, we use the meshgrid function:>> [x y] = meshgrid(-3:0.1:3, 0:0.1:6);
Ï Then calculate z:>> z = cos(x .* y);
Ï Then plot using the mesh command:>> mesh(x, y, z)
Ï To draw a surface instead of a mesh:>> surf(x, y, z)
Ï Selecting a proper spacing (0.1 in our example) is important.
Trevor Spiteri Plotting in MATLAB
PlotsFunctions and Plots
Special Plots
Different Plots3-D Plots
Contours
Ï Topographic plots show contour lines instead of a surface.
Ï To create a contour plot, type:>> contour(x, y, z)
Ï You can draw a mesh and a contour on the same axis using:>> meshc(x, y, z)
Ï You can draw a surface and a contour on the same axis using:>> surfc(x, y, z)
Trevor Spiteri Plotting in MATLAB
top related