Graph-it Help
Back to graphing page.
Many thanks to MathWorks, Inc. for making this all possible.
Table of Contents
Entering equations in Matlab is very similar to how you'd enter them into, say, a graphing calculator. If x was a variable, to multiply it by 2 you'd write: 2*x. To take the sine, sin(x). To store the value of sin(x) in variable z (and you don't have to declare variables ahead of time like you'd do in C or Pascal), you'd type z = sin(x) . Division is / .
Everything in Matlab is a matrix. A constant is a 1 row by 1 column matrix, and a vector either 1 by n (the default in this setting) or n by 1. Later, when things are referred to as matrices, it is meant that each of the row and column dimensions is greater than 1.
Because of this dimensionality, you have to be careful to obey the laws of matrix computation. Suppose t and s are vectors, both 1 by n (where n > 1). You can't just multiply t by s by doing t*s. Why? Because in matrix multiplication, the number of columns of the first must match the number of rows of the second (and the result has the number of rows of the first and the number of columns of the second). t*s would be a (1 by n) * (1 by n), and n is not equal to 1. However, if you wanted to multiply each element of t by its corresponding element in s, the period operator can be utilized before the operator. t.*s would result in a 1 by n vector, with the product of every similary indexed t,s pair.
The period operator is oft-utilized in Matlab. It must be used before the power operator, ^, for example, if a vector is involved. Thus, to square vector t, you'd type t.^2 .
An example of period multiplication: x = [1 2 3 4], y = [5 6 7 8], x.*y gives [5 12 21 32]
Operations such as trigonometric functions, multiplying by constants, or adding constants, work on each matrix element individually. Thus 2*x (of the above x) gives [2 4 6 8], sin(x) gives [0.8415 0.9093 0.1411 -0.7568], and x + 2 gives [3 4 5 6] . Note that the period operator was not needed, since vector operations were not being used.
The matrix transpose operator is a quote: '. Transposing a matrix turns an m by n matrix into an n by m one. Note that for two 1 by n vectors t and s, t'*s returns an n by n matrix, while t*s' returns a single value (1 by 1). (The period operator is not being used here since real matrix multiplication is being done.)
Need to create a new vector of data? You choose the starting point, step value, and the ending point, and Matlab does it for you. x = [0:.1:1] will give a 1 by 11 vector of values between 0 and 1, each separated by .1 . Note that x = [0:.1:1]' will do the same thing, except that it will be an 11 by 1 vector. If you try x = [10:10:1], it returns the empty matrix. Which makes sense, because you're saying add 10 to 10 until you get to 1, which will never happen. Notice also that [0:3:8] will return [0 3 6]; the 8 is not in the vector because the step value went over it without equalling it.
Several of the plots use complex data. To create a complex number, multiply it by i or j (both serve as the square root of -1). I.e. one way to create a vector with real and complex parts is an equation like z = x + y*i .
Finally, here are some of the most important Matlab functions and constants that you may need:
- pi is spelled just like that (Example: pi*r.^2 is the area of a circle)
- eps is the smallest possible number. This is very useful to avoid division by zero
- exp(x) is the exponential of each element of matrix x
- log(x) is the natural logarithm of each element of matrix x, the inverse of the above
- log10(x) is the base-10 logarithm of each element of matrix x
- log2(x) is the base-2 logarithm of each element of matrix x
- sinh(x), cosh(x), and tanh(x) are the hyperbolic trig functions
- asin(x), asinh(x), acos(x), acosh(x), atan(x), and atanh(x) are the inverse trig functions
- ones
- ones(n) creates an n by n matrix of all ones
- ones(m,n) creates an n by m matrix of all ones
- ones(size(x)) creates a matrix, with the same dimensions as x, of all ones
- zeros(...) creates a matrix of all zeros, and it has the same three forms as ones does
- rand(...) creates a matrix of uniformly distributed random numbers, and it comes in the same three forms as ones does
- randn(...) creates a matrix of normally distributed random numbers, and it comes in the same three forms as ones does
- eye(...) creates the identity matrix, and it comes in the same three forms as ones does
- linspace(start, end, numPoints) will declare a 1 by numPoints vector, of evenly spaced points from the start value to the end value. Note that end can be less than start, in which case the vector is decreasing. This is how t and s are created.
- erf(x), the error function, is the integral of the Gaussian distribution function from 0 to x
- eig(x), eigenvalues and eigenvectors. It can be used in several ways:
- d = eig(A) returns a vector d containing the eigenvalues of matrix A
- [v,d] = eig(A) produces a diagonal matrix d of eigenvalues and a full matrix v whose columns are the corresponding eigenvectors so that A*v = v*d
- There are additional uses of eig, such as eig(A,B), to solve A*x = s*B*x, but there is probably no reason to go into that here.
- rem(x,y) is the remainder of x divided by y (actually x./y in the case of vectors)
- floor(x) rounds the elements of x to the nearest integer less than or equal to them
- ceil(x) rounds the elements of x to the nearest integer greater than or equal to them
- round(x) rounds the elements of x
- real(x) extracts the real part of matrix x
- imag(x) extracts the imaginary part of matrix x (Example: if x = 2+3i, imag(x) = 3)
- conj(x) returns the complex conjugate of x, conj(x) = real(x) -i*imag(x)
Back to Linear Graphing
Accepted forms: plot(y), plot(x,y)
- Plot(y) plots the columns of y versus their index. If y is complex, plot(y) is equivalent to plot(real(y), imag(y)).
- Plot(x,y) plots vector x versus vector y. If x or y is a matrix, then the vector is plotted versus the rows or columns of the matrix, whichever line up. Imaginary parts of x and/or y are ignored.
A line color and style may be chosen for this plot.
Example:
t goes from -pi to pi with 1000 data points
x = t
y = tan(sin(t) - sin(tan(t))
Accepted forms: loglog(y), loglog(x,y)
Loglog(...) is the same as plot(...) except logarithmic scales are used for both the x- and y-axes (log-log) scales. See standard 2-D plots for more information.
Accepted forms: semilogx(y), semilogx(x,y)
Semilogx(...) is the same as plot(...) except logarithmic scales are used for the the x-axis and a linear scale for the y-axis. See standard 2-D plots for more information.
Accepted forms: semilogy(y), semilogxy(x,y)
Semilogy(...) is the same as plot(...) except logarithmic scales are used for the the y-axis and a linear scale for the x-axis. See standard 2-D plots for more information.
Accepted forms: polar(t,y)
- Polar(t,y) makes a polar coordinate plot of the angle t, in radians, versus the radius y.
A line color and style may be chosen for this plot.
Example:
t goes from 0 to 2*pi with 500 data points
y = sin(2*t).*cos(2*t)
Accepted forms: bar(y), bar(x,y)
- Bar(y) draws a bar graph of the elements of vector y.
- Bar(x,y) draws a bar graph of the elements in vector y at the locations specified in vector x. The values in x must be evenly spaced and ascending.
A line color and style may be chosen for this plot.
Example:
t goes from -2.9 to 2.9 with 30 data points
x = t
y = exp(-x.*x)
Accepted forms: stairs(y), stairs(x,y)
- Stairs(y) draws a stairstep graph of the elements of vector y. A stairstep graph is similar to a bar graph, but the vertical lines dropping to the x-axis are omitted.
- Stairs(x,y) draws a stairstep graph of the elements in vector y at the locations specified in vector x. The values in x must be evenly spaced and ascending.
A linestyle may not be chosen for this plot. It is suggested that the background be turned to black.
Example:
t goes from 0 to 10 with 40 data points
x = t
y = sin(x)
Accepted forms: hist(y), hist(y,x)
- Hist(y) draws a 10-bin histogram for the data in vector y. The bins are equally spaced between the minimum and maximum values in y.
- Hist(y,x) draws a histogram of the data in vector y using the bins specified in the vector x.
A linestyle may not be chosen for this plot. It is suggested that the background be turned to black.
Example:
t goes from -2.9 to 2.9 with 60 data points
x = t
y = randn(10000,1)
Accepted forms: stem(y), stem(x,y)
- Stem(y) plots the data sequence y as stems from the x-axis. Each stem is terminated with a circle whose y-position represents the data value.
- Stem(x,y) plots the data sequence y at the values specified in x.
A line color and style may be chosen for this plot.
Example:
y = randn(50,1) % ignore t in this case
Accepted forms: errorbar(x,y,z)
- Errorbar(x,y,z) plots the graph of vector x versus vector y with errorbars specified by vector z. Vectors x,y, and z must be the same length. The error bars are each drawn a distance of z(i) above and below the points in (x,y) so that each bar is 2*e(i) long. If x, y, and z are matrices of the same size, one errorbar graph per column is drawn.
A linestyle may not be chosen for this plot. It is suggested that the background be turned
to black.
Example:
t goes from 0 to 10 with 50 data points
x = t
y = sin(t)
z = erf(x) % erf, the error function, is the integral of the Gaussian distribution
function from 0 to x
Accepted forms: compass(y), compass(x,y)
- Compass(y) draws a graph that displays the angle and magnitude of the complex elements of y as arrows emanating from the origin.
- Compass(x,y) is equivalent to compass(x + i*y). It displays the compass plot for the angles and magnitudes of the elements of matrices x and y.
A line color and style may be chosen for this plot.
Example 1:
t goes from -10 to 10 with 50 data points
x = t
y = sin(cos(t))
Example 2:
y = eig(randn(20,20)) % ignore t, eig returns the eigenvalues of the matrix
Accepted forms: feather(y), feather(x,y)
- Feather(y) draws a graph that displays the angle and magnitude of the complex elements of y as arrows emanating from equally spaced points along a horizontal axis.
- Feather(x,y) is equivalent to feather(x + i*y). It displays the feather plot for the angles and magnitudes of the elements of matrices x and y.
A line color and style may be chosen for this plot.
Example:
t goes from 0 to 2*pi with 50 data points
x = t
y = 10*randn(1,50)
Accepted forms: rose(t,y)
- Rose(t,y) plots an angle histogram for the angles in t, which must be in radians. The angle histogram is a plot in polar coordinates of the number of theta points or samples within the bins specified by vector y. The values in y specify the center angle of each bin.
A linestyle may not be chosen for this plot. It is suggested that the background be turned to black.
Example:
t goes from -pi to pi with 50 data points
y = log(cos(exp(t.^(-2))))
Accepted forms: fill(x,y)
- Fill(x,y) fills the two-dimensional polygon defined by vectors x and y with the color specified. The vertices of the polygon are specified by pairs of components of x and y. If necessary, the polygon are specified by pairs of components of x and y. If necessary, the polygon is closed by connecting the last vertex to the first. If x and y are matrices of the same size, fill(x,y) will draw one polygon per column.
A line color and shading may be chosen for this plot.
Example:
t goes from 0 to 2*pi with 8 data points
x = sin(t)
y = cos(t)
Accepted forms: plot3(x,y,z)
- Plot3(x,y,z), where x, y, and z are three vectors of the same length, plots a line in 3-D space through the points whose coordinates are the elements of x, y, and z. If x, y, and z are three matrices of the same size, plot3 plots several lines obtained from the columns of x,y, and z.
A line color and style may be chosen for this plot.
Example:
t goes from 0 to 2*pi with 50 data points
x = sin(t)
y = cos(t)
z = t
Accepted forms: fill3(x,y,z)
- Fill3(x,y,z) fills the three-dimensional polygon defined by vectors x, y, and z with the color specified. The vertices of the polygon are specified by triples of components of x, y, and z. If necessary, the polygon is closed by connecting the last vertex to the first. If x, y, and z are matrices of the same size, fill(x,y,z) draws one polygon per column.
A line color and shading may be chosen for this plot.
Example:
t goes from 0 to 2*pi with 50 data points
x = sin(t)
y = cos(t)
z = tan(t)
Back to Surface Graphing.
There are a few items that need additional discussion here:
- Cylinder(z,n) generates the (x,y,z) coordinates of a unit cylinder, based on the generator curve in the vector z (don't be confused by the renaming of z in the x,y,z generated). z contains the radius at equally spaced points along the unit height of the cylinder. The cylinder generated is aligned with the z-axis. The cylinder has n points around the circumference. Note that to have a differing number of points in the vector z than in the number of points around the circumference, base z on the time variable s instead.
- Sphere(n) generates the (x,y,z) coordinates of a unit sphere. It will look warped without 'axis square' chosen in the plot controls section.
- Meshgrid(x,y) transforms the domain specified by vectors x and y into matrices x and y (once again, a renaming; once you meshgrid x and y into matrices, you can't use the old x and y vectors anymore (in say, z). These matrices can be used for the evaluation of functions of two variables and three dimensional surface-type plots. The rows of the output matrix x are copies of vector x and the columns of the output matrix y are copies of the vector y.
- A colormap is matrix of real numbers between 0.0 and 1.0 with 3 columns. The k-th row of the colormap defines the k-th color by specifying the intensity of red, green, and blue. The way the colormap is accessed is by the use of a color matrix, c, with a linear mapping. c is optional, and if not specified, z is used instead, so color corresponds to height along the z-axis.
- If you type in classical parametric equations, such as that of a sphere, with the .* notation, do not expect to see the object you're expecting. Remember that multiplication with the . is not a mathematically valid vector operation. To see how to create a sphere, see the example at the end. Usually, a matrix for each of x,y, and z must be created in these cases.
Accepted forms: contour(z), contour(x,y,z)
- Contour(z) draws a contour plot of matrix z. The contours are level lines in the units of array z. The lower-left corner of the plot corresponds to z(1,1). The number of contour lines and their values are chosen automatically.
- Contour(x,y,z) draws a contour plot of matrix z, using the data in vectors x and y to control the axis scaling on the x- and y- axes. The elements of x and y are equally spaced.
Example:
To view a contour plot of the function z = x*exp(-x.^2 - y.^2) with parameters as indicated:
t goes from -2 to 2 with 20 points
s goes from -2 to 3 with 25 points
x = t
y = s
choose yes on meshgrid
z = x.*exp(-x.^2 - y.^2) % note that meshgrid will change x and y to matrices after the meshgrid; this will not be a problem, contour will just use the first row it can find
Accepted forms: contour3(z), contour3(x,y,z)
- Contour3(z) plots the contour lines of z in three-dimensional format.
- Contour3(x,y,z) use matrices x and y to define the axes limits. x and y can be vectors, too, in which case they are expanded to matrices by replicating rows and columns, respectively.
Example:
t goes from -3 to 3 with 50 points % s will not be used
x = t
y = t
choose yes on meshgrid
z = peaks(x,y) % peaks is a built-in function that produces very interesting matrices for plotting
Accepted forms: pcolor(z), pcolor(x,y,z)
- Pcolor(z) draws a pseudocolor plot, a rectangular array of cells with colors determined by the elements of z. A pseudocolor plot is actually a surface plot seen from the top.
- Pcolor(x,y,z) with two vector arguments must have length(x) = n and length(y) = m where [m,n] = size(z). The spacing of the grid lines is set by x and y, so the grid lines are straight, but not necessarily evenly spaced. Note that x corresponds to the columns of z and y corresponds to the rows. x and y may be matrices as well (so meshgrid is truly optional).
A colormap and shading may be chosen for this plot.
Example:
t goes from 0 to 6 with 7 data points
s goes from -6 to 6 with 13 data points
place in optional area 1: r = t/n
place in optional area 2: theta = pi*s/n
x = r'*cos(theta) % produces a matrix 7 by 13
y = r'*sin(theta)
choose no on meshgrid
z = r'*cos(2*theta)
choose axis square
Accepted forms: mesh(z), mesh(z,c), mesh(x,y,z), mesh(x,y,z,c)
- Mesh(z) draws a mesh plot (colored grid lines) of the matrix z, using the row and column indices of z for x and y. Color, c, is z, so it is proportional to surface height.
- Mesh(z,c) is as above, but the color index is specified specifically by matrix c.
- Mesh(x,y,z) plots the colored grid lines on the parametric surface specified by x, y, and z. x and y can be vectors or matrices (so meshgrid is optional). z is also used to specify the color index, so the color is proportional to surface height.
- Mesh(x,y,z,c) is as above, but the color index is specified specifically by matrix c.
A colormap and shading may be chosen for this plot.
Example:
t goes from -7.5 to 7.5 with 30 data points % s is not used
x = t
y = t
choose yes on meshgrid
place in optional area 3: r = sqrt(x.^2 + y.^2) + eps % eps is used to prevent division by zero.
z = sin(r)./r
Accepted forms: meshc(z), meshc(z,c), meshc(x,y,z), meshc(x,y,z,c)
Meshc(...) is the same as mesh(...) except that a contour plot is drawn beneath the mesh. See mesh plots for more information.
Accepted forms: meshz(z), meshz(z,c), meshz(x,y,z), meshz(x,y,z,c)
Meshz(...) is the same as mesh(...) except that a curtain plot, or reference plane, is drawn beneath the mesh. See mesh plots for more information.
Accepted forms: waterfall(z), waterfall(z,c), waterfall(x,y,z), waterfall(x,y,z,c)
Waterfall(...) is the same as mesh(...) except that it omits the column lines of the plot to produce a "waterfall" effect. See mesh plots for more information.
Accepted forms: surf(z), surf(z,c), surf(x,y,z), surf(x,y,z,c)
Surf(...) is the same as mesh(...) except that whereas the other draws grid lines, this draws the actual colored parametric surface. See mesh plots for more information.
Accepted forms: surfc(z), surfc(z,c), surfc(x,y,z), surfc(x,y,z,c)
Surfc(...) is the same as surf(...) except that a contour plot is drawn beneath the surface. See surface plots for more information.
Accepted forms: surfl(z), surfl(x,y,z), surfl(x,y,z,S), surfl(x,y,z,S,K)
Surfl(...) is the same as surf(...) except that it produces a shaded surface plot based on a combination of diffuse, specular, and ambient lighting models. It is recommended to view the surfaces with a grayscale or similar colormap (such as gray, copper, bone, or pink). See surface plots for more information.
- Surfl(x,y,z,S) uses vector S (not the parametric variable) to determine the direction of the light source. S accepts two spherical coordinates, the azimuth and the elevation. Azimuth describes the angle in the x-y plane, measured in degrees from the negative y-axis. Elevation describes the angle in degrees at which you observe the plot above the x-y plane.
- Surfl(x,y,z,S,K) uses vector S as above, and an additional vector K that specifies the contribution due to ambient light (ka), diffuse reflection (kd), specular reflection (ks), and the specular spread coefficient (spread).
Example:
z = peaks(20) % just ignore everything else
choose colormap gray
use the default lighting given
choose interp shading
Accepted forms: surfnorm(z), surfnorm(x,y,z)
Surfnorm(...) is the same as surf(...) except that the unnormalized surface normals are included in the graph as well. See surface plots for more information.
Example:
t goes from 0 to 2*pi with 20 data points
choose cylinder instead of entering equations
z = 2 + cos(t)
Back to Plot Controls .
- Shading controls the color shading (only for surface, mesh, pcolor, fill, and fill3 plots).
- Flat shading is piecewise constant; each mesh line segment or surface patch has a constant color determined by the color values at the end points of the segment or the corners of the patch.
- Faceted shading is the default. It is flat shading with super-imposed black mesh lines.
- Interpolate shading, also known as Gouraud shading, is piecewise bilinear; the color in each segment or patch varies linearly and interpolates the end or corner values. NOTE: this form of shading is the most calculation-intensive, and do not try to use more than 30 points.
- Viewpoint specification (azimuth, elevation) sets the viewing angle for a three-dimensional plot. The azimuth is the horizontal rotation and elevation is the vertical elevation (both in degrees). Azimuth revolves about the z-axis, with positive values indicating counter-clockwise rotation of the viewpoint. Positive values of elevation correspond to moving above the object; negative values move below.
- Axis
- The default is to accomodate the minimum and maximum values of each x,y,z point, so that all points fit on the plot.
- Square sets the current axes region to be square (default is rectangle). Good for sphere, because the default rectangle warps them.
- Equal indicates that the scaling factors and tic mark increments for the axes are equal.
- The manual choice allows you to scale the axes to the minimums and maximums that you enter. Note that you must enter all 4 values for a 2-D plot, and 6 for a 3-D plot, even if all you want to do is set one axis.
- The text entered in the title area goes above the plot.
- The background of the plot can be white or black.
One of my favorite examples, and one of the best to describe parametric surfaces
choose 2-variable, and surface plot
t goes from -31 to 31 with 31 points % ignore s
place in optional area 1: theta = pi*t/n
place in optional area 2: phi = (pi/2)*t/n
x = cos(phi)'*cos(theta)
y = cos(phi)'*sin(theta)
choose no on meshgrid
z = sin(phi)'*ones(size(theta)) % must be a matrix
c = hadamard(n+1) % hadamard is a function which returns a matrix of 1's and -1's
choose axis square
Note that although s was ignored, this is still very much a function of two variables, theta and phi. s was ignored because both theta and phi use the same angle vector, t.
Also try mixing up the order; i.e. put
z = hadamard(n+1)
c = sin(phi)'*ones(size(theta))
Nearly every definition above came out of:
"The Student Edition of Matlab, Version 4 User's Guide", MathWorks Inc., Prentice Hall, Englewood Cliffs, NJ 07632, 1995
(although the interface is with the professional version)
The hadamard-sphere example came out of:
"MATLAB User's Guide for UNIX workstations", MathWorks, Inc., 1992.
Return to Graphing Equations .
Return to Ken's Home Page .