You are on page 1of 58

TUTORIAL MEMBUAT GRAFIK 3D DENGAN MATLAB

Di postingan sebelumnya kita telah banyak membahas bagaimana cara membuat grafik dengan software matlab, tapi kali ini kita mencoba membuat grafik dengan 3D yang menarik dari sebuah fungsi matematika. Seperti kita ketahui bahwa Matlab merupakan bahasa pemrograman level tinggi yang dikhususkan untuk kebutuhan komputasi teknis, visualisasi dan pemrograman seperti komputasi matematik, analisis data, pengembangan algoritma, simulasi dan pemodelan dan grafik-grafik

perhitungan.Sehingga inilah yang menyebabkan matlab mudah digunakan dalam pemodelan simulasi kurva ataupun grafik. Berikut cara pembuatan program grafik tiga dimensi ( 3D) pada Matlab 6.5, dimana fungsi matematika dari grafik tersebut adalah Z = (X2 + Y2): 1. Bukalah aplikasi matlab yang sudah terinstall di PC anda, kemudian pilih >> New MFile (Ctrl-N) 2. Ketikkan script / kode / listing program matlab berikut ini : sumbu_x = -10:1:10; sumbu_y = -10:4:10; [X,Y] = meshgrid(sumbu_x,sumbu_y); Z = X.^2 + Y.^2; mesh(X,Y,Z); 3. Kemudian Save dan Run (F5), Berikut hasil grafiknya :

Gambar Grafik tiga dimensi (3D) pada matlab dengan perintah mesh 4. Setelah berhasil coba pada tahap kedua ganti kode mesh dengan surf. Maka berikut grafik hasilnya :

Gambar Grafik tiga dimensi (3D) pada Matlab dengan perintah surf 5. Dan anda juga dapat merubahnya dengan perintah contour. Grafik akan menjadi seperti ini :

Gambar Grafik tiga dimensi (3D) pada Matlab dengan perintah contour 6. Good Luck.!!!

Notes : Penjelasan Program Grafik tiga dimensi (3D) pada tahap kedua diatas : Baris 1 : batas nilai x yang akan di plot Baris 2 : batas nilai y yang akan di plot Baris 3 : mengisi bidang X dan Y dengan jalinan titik Baris 4 : fungsi matematika yang akan diplot yaitu Z = (X2 + Y2) Baris 5 : Perintah program Matlab untuk menampilkan grafik 3D

Surfaces and Grids in Matlab The ability to handle surfaces and grids is one of Matlabs many strengths. Since a lot of geologic data is naturally of more than one dimension, we have use for these capabilities. Surfaces A surface is a set of polygons. They are easy to plot in Matlab. Because data is often not regularly sampled, surfaces are often modeled as a set of interlocking triangles. There is a particularly compact way of making surfaces of irregularly spaced data called a Delaunay triangulation. Delaunay triangulation is the set of triangles built by connecting each of the points of an irregularly spaced data set where the vertices of the triangles are the data points. Thus it is an exact representation of your known data and linear interpolation in between. To see what we mean, load up the dmap.dat data file from the Q:\geo185 directory by typing load dmap.dat This is an X,Y,Z elevation data file for columns 1,2,3. First visualize the file with the plot3 command >> p_h=plot3(dmap(:,1),dmap(:,2),dmap(:,3),'o') The 'o' parameter plots the data points as individual circles as opposed to a 3D-line. The p_h is called a handle. You could have just typed plot3 without the p_h but by adding this you have the ability to later delete this graphic element

>> hold on This keeps the plot held for more plotting Now in order to plot the data as a triangulated surface we need to build the surface first with: >>tri=delaunay(dmap(:,1),dmap(:,2)) This creates a n x 3 matrix of the vertice row entries that are needed for each triangle to visualize this triangulated surface type: >> trisurf(tri,dmap(:,1),dmap(:,2),dmap(:,3))

Note that the vertex of each triangle is one of the data points. If you want to see the plot without the points type: >>delete(p_h) This surface plot is efficient but it doesnt produce a very pretty picture (well at least for this small data set, for large data sets, triangulated surfaces are often preferable because they are more compact and there is enough data that the surface looks good). Grids So we often want a regular spacing of the X and Y locations to make it smoother and not faceted. A regularly spaced data set is called a grid. It uses up more memory and thus is slower to manipulate because data is defined at every location. To convert the irregularly spaced data to regularly spaced we need to grid it. This requires a couple of steps. First you need to define the spacing and extent of the grid by making two vectors of the X and Y upper and lower limits at a given spacing: >> rangeY=floor(min(dmap(:,2))):.2:ceil(max(dmap(:,2))) >>rangeX=floor(min(dmap(:,1))):.2:ceil(max(dmap(:,1)))

0.2 is the spacing I have chosen. I was a little obscure in choosing the floor(min syntax. Try min(dmap(:,2)) to see what that gives you and then try floor(min(dmap(:,2))) to see what that does. Hint: it is a way of controlling the rounding direction. Now make matrices for each X and Y location: >>[X,Y]=meshgrid(rangeX,rangeY) And then interpolate your Z values across this grid: >>Z=griddata(dmap(:,1),dmap(:,2),dmap(:,3),X,Y) To see the result: >>surf(X,Y,Z)

For a smoother interpolation add the cubic spline parameter: >>Z=griddata(dmap(:,1),dmap(:,2),dmap(:,3),X,Y,'cubic') >>surf(X,Y,Z)

Note that the grid values in between the data points vary smoothly and no longer have the facets we saw with the triangulated surface. If you want to make a contour plot of the gridded data you can do this by first defining the range and spacing of the Z values: >>rangeZ=floor(min(dmap(:,3))):10:ceil(max(dmap(:,3))) Then running: >>[C,h]=contour(X,Y,Z,rangeZ)

This makes a 2-D contour plot. Again you could left off the [C,h] as this is a handle, but it is useful for labeling the contour lines: >>c_h=clabel(C,h,rangeZ(1:2:end)) I chose to take every other value within rangeZ

You can actually combine contours and surfaces and make your surface plot look better and with no grid lines: >>surf(X,Y,Z,'EdgeColor','none','FaceColor','interp','FaceLighting','phong') And then add 3-D contour lines: >> contour3(X,Y,Z,rangeZ,'k')

There are many more possible plots with surfaces and grids. I strongly urge you to look at the help files.

1. The problem statement, all variables and given/known data Suppose f(x,y) = sin(3y-x^2+1)+cos(2y^2-2x) a) produce a labeled contour plot for -2 <= x <= 2, -1<= y<= 1 b) Based on the contour plot you found in a) estimate the coordinates of two saddle points of the function in the region S defined in a). Mark the points using the Data Cursor. 2. Relevant equations 3. The attempt at a solution I will attach my code and output image Code:
x=linspace (-2,2,25); y=linspace (-1,1,25); [x y]=meshgrid (x,y) z = sin(3.*y - x.^2 + 1) + cos(2.*y.^2 - 2.*x); [C h]=contour (x,y,z); % the "handle" matrix [C h] holds the graph for labelling clabel (C,h); % the clabel function labels the level curves

I don't really know how to tell from the graph. I tried to solve it using second derivative test in matlab, but the solution is very weird, which I can't really use it at this point. Is it true that the the gap (pointy-gap) between the two lightest green lines are the two

saddle points??? Any help is appreciated. Thank you

science news on PhysOrg.com PhysOrg.com >> Seeing beyond cameras: Predicting where people move in CCTV blind spots >> Black holes growing faster than expected >> Digging yields clues: Biologists connect burrowing behavior in mice to genes Re: matlab & saddle point #2 Yes, it's the green "pointy-gap" parts. And good job on the matlab programming. If you go through on a line through the two green pointy gaps it looks like minimum. If you go through at approximately a 90 degree angle to that it looks like a maximum. Isn't that a saddle point?

Jul5-10, 10:43 PM Dick

Recognitions: Homework Helper Science Advisor

Jul510, 11:04 PM jwxie @ Dick thank you, I really have one more simple problem. Code:
x= linspace(0, 2, 15);y= linspace(0,2,15); [x y]= meshgrid(x,y); z=sin(3.*x+y)+ 2.*cos(x-y); [C h] = contour(x,y,z);clabel(C,h);

Re: matlab & saddle point #3

hold on surfc (x,y,z); view ([1 1 1]) title('Yeukhon Wong, Ex. 5.3, Contour Plot of z=(3*x+y)-2*cos(xy)'); hold off

output: http://i49.tinypic.com/30d8dwj.jpg

This time we are suppose to do the following: Based on the contour plot you found in a) determine whether the function has any critical points in the square S defined in a). If there are any such points, provide estimates from the graph for their x and y coordinates and provide a justification from the graph as to whether these are relative maximum , minimum or saddle points. I think the darkest red is the maximum line, and its middle point is a good estimation of point of maximum ; the darkest blue is the min line, and the last portion of the line is probably a good estimation of point of minimum . The saddle point, again, is the green pointy-gap. Actually I think a good estimation would be the sharp point. What do you think? Thank you so much!

from MATLAB Plot Gallery - Surface Contour Plot by Plot Gallery Create a surface contour plot Surface_Contour_Plot This is an example of how to create a surface contour plot in MATLAB. Read about the surfc function in the MATLAB documentation. Go to MATLAB Plot Gallery
% Create a grid of x and y data y = -10:0.5:10; x = -10:0.5:10; [X, Y] = meshgrid(x, y); % Create the function values for Z = f(X,Y) Z = sin(sqrt(X.^2+Y.^2)) ./ sqrt(X.^2+Y.^2); % Create a surface contour plor using the surfc function figure; surfc(X, Y, Z); % Adjust the view angle view(-38, 18); % Add title and axis labels title('Normal Response'); xlabel('x'); ylabel('y'); zlabel('z');

Copyright 2012 The MathWorks, Inc. Published with MATLAB 7.14 Contact us at files@mathworks.com

surfc
Contour plot under a 3-D shaded surface plot

Syntax
surfc(Z) surfc(Z,C) surfc(X,Y,Z) surfc(X,Y,Z,C) surfc(...,'PropertyName',PropertyValue) surfc(axes_handles,...) h = surfc(...)

Description
surfc(Z)

creates a contour plot under the three-dimensional shaded surface from the z components in matrix Z, using x = 1:n and y = 1:m, where [m,n] = size(Z). The height, Z, is a single-valued function defined over a geometrically rectangular grid. Z specifies the color data, as well as surface height, so color is proportional to surface height.
surfc(Z,C)

plots the height of Z, a single-valued function defined over a geometrically rectangular grid, and uses matrix C, assumed to be the same size as Z, to color the surface.
surfc(X,Y,Z) uses Z for the color data and surface height. X and Y are vectors or matrices defining the x and y components of a surface. If X and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). In this case, the vertices of the surface faces are (X(j), Y(i), Z(i,j)) triples. To create X and Y matrices for arbitrary domains, use the meshgrid

function.
surfc(X,Y,Z,C)

uses C to define color. MATLAB performs a linear transformation on this data to obtain colors from the current colormap.
surfc(...,'PropertyName',PropertyValue)

specifies surface Surfaceplot along with the

data.
surfc(axes_handles,...) current axes (gca). h = surfc(...)

plots into the axes with handle axes_handle instead of the

returns a handle to a Surfaceplot graphics object.

Examples
Display a surface plot and a contour plot of the peaks surface.

[X,Y,Z] = peaks(30); surfc(X,Y,Z) colormap hsv axis([-3 3 -3 3 -10 5])

More About
expand all

Tips Algorithms

Representing a Matrix as a Surface Coloring Mesh and Surface Plots

See Also
axis | caxis | colormap | contour | delaunay | imagesc | mesh | meshgrid | pcolor shading | surf | Surfaceplot Properties | trisurf | view

ezmesh
Easy-to-use 3-D mesh plotter

Syntax
ezmesh(fun) ezmesh(fun,domain) ezmesh(funx,funy,funz) ezmesh(funx,funy,funz,[smin,smax,tmin,tmax]) ezmesh(funx,funy,funz,[min,max] ezmesh(...,n) ezmesh(...,'circ') ezmesh(axes_handle,...) h = ezmesh(...)

Description
ezmesh(fun)

creates a graph of fun(x,y) using the mesh function. fun is plotted over the default domain: -2 < x < 2, -2 < y < 2.
fun

can be a function handle or a string (see the Tips section).

ezmesh(fun,domain) plots fun over the specified domain. domain can be either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where min < x < max, min < y < max). ezmesh(funx,funy,funz) plots the parametric surface funx(s,t), funy(s,t), funz(s,t) over the square: -2 < s < 2, -2 < t < 2. ezmesh(funx,funy,funz,[smin,smax,tmin,tmax]) or ezmesh(funx,funy,funz,[min,max]) plots the parametric surface using

and

the specified

domain.
ezmesh(...,n) n is 60.

plots fun over the default domain using an n-by-n grid. The default value for

ezmesh(...,'circ')

plots fun over a disk centered on the domain. plots into the axes with handle axes_handle instead of the

ezmesh(axes_handle,...) current axes (gca). h = ezmesh(...)

returns the handle to a surface object in h.

Examples
This example visualizes the function

with a mesh plot drawn on a 40-by-40 grid. The mesh lines are set to a uniform blue color by setting the colormap to a single color:
fh = @(x,y) x.*exp(-x.^2-y.^2); ezmesh(fh,40) colormap([0 0 1])

ezmeshc
Easy-to-use combination mesh/contour plotter

Syntax
ezmeshc(fun) ezmeshc(fun,domain) ezmeshc(funx,funy,funz) ezmeshc(funx,funy,funz,[smin,smax,tmin,tmax]) ezmeshc(funx,funy,funz,[min,max]) ezmeshc(...,n) ezmeshc(...,'circ') ezmesh(axes_handle,...) h = ezmeshc(...)

Description
ezmeshc(fun)

creates a graph of fun(x,y) using the meshc function. fun is plotted over the default domain -2 < x < 2, -2 < y < 2.
fun

can be a function handle or a string (see the Tips section).

ezmeshc(fun,domain) plots fun over the specified domain. domain can be either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where min < x < max, min < y < max). ezmeshc(funx,funy,funz) plots the parametric surface funx(s,t), funy(s,t), funz(s,t) over the square: -2 < s < 2, -2 < t < 2. ezmeshc(funx,funy,funz,[smin,smax,tmin,tmax]) or ezmeshc(funx,funy,funz,[min,max]) plots the parametric surface using

and

the specified

domain.
ezmeshc(...,n) for n is 60.

plots fun over the default domain using an n-by-n grid. The default value

ezmeshc(...,'circ')

plots fun over a disk centered on the domain. plots into the axes with handle axes_handle instead of the

ezmesh(axes_handle,...) current axes (gca). h = ezmeshc(...)

returns the handle to a surface object in h.

Examples
Create a mesh/contour graph of the expression

over the domain -5 < x < 5, -2*pi < y < 2*pi:


ezmeshc('y/(1 + x^2 + y^2)',[-5,5,-2*pi,2*pi]) view(-65.5,26)

Use the mouse to rotate the axes to better observe the contour lines (this picture uses a view of azimuth = -65.5 and elevation = 26)

ezsurfc
Easy-to-use combination surface/contour plotter

Syntax
ezsurfc(fun) ezsurfc(fun,domain) ezsurfc(funx,funy,funz) ezsurfc(funx,funy,funz,[smin,smax,tmin,tmax]) ezsurfc(funx,funy,funz,[min,max] ezsurfc(...,n) ezsurfc(...,'circ') ezsurfc(axes_handle,...) h = ezsurfc(...)

Description
ezsurfc(fun)

creates a graph of fun(x,y) using the surfc function. The function fun is plotted over the default domain: -2 < x < 2, -2 < y < 2.
fun

can be a function handle or a string (see the Tips section).

ezsurfc(fun,domain) plots fun over the specified domain. domain can be either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where min < x < max, min < y < max). ezsurfc(funx,funy,funz) plots the parametric surface funx(s,t), funy(s,t), funz(s,t) over the square: -2 < s < 2, -2 < t < 2. ezsurfc(funx,funy,funz,[smin,smax,tmin,tmax]) or ezsurfc(funx,funy,funz,[min,max]) plots the parametric surface using

and

the specified

domain.
ezsurfc(...,n)

plots f over the default domain using an n-by-n grid. The default value for n

is 60.
ezsurfc(...,'circ')

plots f over a disk centered on the domain. plots into the axes with handle axes_handle instead of the

ezsurfc(axes_handle,...) current axes (gca). h = ezsurfc(...)

returns the handles to the graphics objects in h.

Examples
Create a surface/contour plot of the expression

over the domain -5 < x < 5, -2*pi < y < 2*pi, with a computational grid of size 35-by-35:
ezsurfc('y/(1 + x^2 + y^2)',[-5,5,-2*pi,2*pi],35)

Put the plot in rotate3d mode to use the mouse to rotate the axes to better observe the contour lines (this picture uses a view of azimuth = -65.5 and elevation = 26).

surfl
Surface plot with colormap-based lighting

Syntax
surfl(Z) surfl(...,'light') surfl(...,s) surfl(X,Y,Z,s,k) h = surfl(...)

Description
The surfl function displays a shaded surface based on a combination of ambient, diffuse, and specular lighting models.
surfl(Z)

and surfl(X,Y,Z) create three-dimensional shaded surfaces using the default direction for the light source and the default lighting coefficients for the shading model. X, Y, and Z are vectors or matrices that define the x, y, and z components of a surface.
surfl(...,'light')

produces a colored, lighted surface using a MATLAB light object. This produces results different from the default lighting method, surfl(...,'cdata'), which changes the color data for the surface to be the reflectance of the surface.
surfl(...,s)

specifies the direction of the light source. s is a two- or three-element vector that specifies the direction from a surface to a light source. s = [sx sy sz] or s = [azimuth elevation]. The default s is 45 counterclockwise from the current view direction.
surfl(X,Y,Z,s,k)

specifies the reflectance constant. k is a four-element vector defining the relative contributions of ambient light, diffuse reflection, specular reflection, and the specular shine coefficient. k = [ka kd ks shine] and defaults to [.55,.6,.4,10].
h = surfl(...)

returns a handle to a surface graphics object.

Examples
View peaks using colormap-based lighting.
[x,y] = meshgrid(-3:1/8:3); z = peaks(x,y); surfl(x,y,z); shading interp colormap(gray); axis([-3,3,-3,3,-8,8])

To plot a lighted surface from a view direction other than the default,
view([10 10]) grid on hold on surfl(peaks) shading interp colormap copper hold off

surfnorm
Compute and display 3-D surface normals

Syntax
surfnorm(Z) surfnorm(X,Y,Z) surfnorm(axes_handle,___) surfnorm(___,Name,Value) [Nx,Ny,Nz] = surfnorm(___)

Description
surfnorm(Z)

plots a surface of the matrix Z with surf and displays its surface normals as radiating vectors.
surfnorm(X,Y,Z) plots a surface and its surface and matrix Z. X, Y, and Z must be the same size. surfnorm(axes_handle,___)

normals from the vectors or matrices X, Y,

plots into axes_handle instead of gca and it can include any of the input arguments in previous syntaxes.
surfnorm(___,Name,Value) Properties.

can be used to set the value of the specified Surface

[Nx,Ny,Nz] = surfnorm(___)

returns the components of the 3-D surface normals for the surface without plotting the surface or surface normals.

Input Arguments
Z X Y axes_handle

2D array of real numbers representing a surface 2D array of real numbers that defines the x component of the surface grid 2D array of real numbers that defines the y component of the surface grid Handle to the target axes in which to plot the surface If you do not specify axes_handle, MATLAB uses current axes.

Name,Value

Specify optional comma-separated pairs of Name,Value arguments, where Name is the argument name and Value is the corresponding value. Name must appear inside single quotes (' '). You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN. Property names and values of the surface object

See Surface Properties for description of property names and values.

Output Arguments
[Nx,Ny,Nz]

x, y, and z components of the three-dimensional surface normals for the surface

Examples
Plot the normal vectors for a truncated cone.
[x,y,z] = cylinder(1:10); surfnorm(x,y,z) axis([-12 12 -12 12 -0.1 1])

Get normal vectors of an expression representing a surface.


[nx, ny, nz] = surfnorm(peaks);

You can use these normals in conjunction with VertexNormals property and to apply lighting variations to a plain surface as,
b = reshape([nx ny nz], 49,49,3);

surf(ones(49), 'VertexNormals', b);%Create a plain surface of size equal to peaks. shading interp % remove edge definition from the image camlight

meshc
Plot a contour graph under mesh graph

Syntax
meshc(X,Y,Z) meshc(Z) meshc(...,C) meshc(axes_handles,...) h = meshc(...)

Description
meshc(X,Y,Z) draws a wireframe mesh and a contour plot under it with color determined by Z, so color is proportional to surface height. If X and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). In this case, (X(j), Y(i), Z(i,j)) are the intersections of the wireframe grid lines; X and Y correspond to the columns and rows of Z, respectively. If X and Y are matrices, (X(i,j), Y(i,j), Z(i,j)) are the intersections of the

wireframe grid lines.


meshc(Z) draws a contour plot under wireframe mesh using X = 1:n and Y = 1:m, where [m,n] = size(Z). The height, Z, is a single-valued function defined over a rectangular grid.

Color is proportional to surface height.


meshc(...,C)

draws a meshc graph with color determined by matrix C. MATLAB performs a linear transformation on the data in C to obtain colors from the current colormap. If X, Y, and Z are matrices, they must be the same size as C.
meshc(axes_handles,...) current axes (gca). h = meshc(...)

plots into the axes with handle axes_handle instead of the

returns a handle to a Surfaceplot graphics object.

Examples
Produce a combination mesh and contour plot of the peaks surface with meschc:
figure [X,Y] = meshgrid(-3:.125:3); Z = peaks(X,Y); meshc(Z);

Specifying axes limits for the meshc function.


figure; meshc(X,Y,Z); axis([-3 3 -3 3 -10 5]);

Search R20

MATLAB ... 2-D and 3-D Plots Surfaces, Volumes, and Polygons Surface and Mesh Plots

meshz
Plot a curtain around mesh plot

Syntax
meshz(X,Y,Z) meshz(Z) meshz(...,C) meshz(axes_handles,...) h = meshz(...)

Description
meshz(X,Y,Z)

draws a curtain around the wireframe mesh with color determined by Z, so color is proportional to surface height. If X and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). In this case, (X(j), Y(i), Z(i,j)) are the intersections of the wireframe grid lines; X and Y correspond to the columns and rows of Z, respectively. If X and Y are matrices, (X(i,j), Y(i,j), Z(i,j)) are the intersections of the wireframe grid lines.
meshz(Z) draws a curtain around the wireframe mesh using X = 1:n and Y = 1:m, where [m,n] = size(Z). The height, Z, is a single-valued function defined over a rectangular grid.

Color is proportional to surface height.


meshz(...,C)

draws a meshz graph with color determined by matrix C. MATLAB performs a linear transformation on the data in C to obtain colors from the current colormap. If X, Y, and Z are matrices, they must be the same size as C.
meshz(axes_handles,...) current axes (gca). h = meshz(...)

plots into the axes with handle axes_handle instead of the

returns a handle to a Surfaceplot graphics object.

Examples
Generate a curtain plot for the peaks function using meshz
figure [X,Y] = meshgrid(-3:.125:3); Z = peaks(X,Y); meshz(Z);

Specifying axes limits for the graph


figure; meshz(X,Y,Z); axis([-3 3 -3 3 -7 9]);

Specifying a color matrix


C = gradient(Z); figure; meshz(X,Y,Z,C);

contour3
3-D contour plot

Syntax
contour3(Z) contour3(Z,n) contour3(Z,v) contour3(X,Y,Z) contour3(X,Y,Z,n) contour3(X,Y,Z,v) contour3(...,LineSpec) contour3(axes_handle,...) [C,h] = contour3(...)

Description
contour3

creates a 3-D contour plot of a surface defined on a rectangular grid.

contour3(Z)

draws a contour plot of matrix Z in a 3-D view. Z is interpreted as heights with respect to the x-y plane. Z must be at least a 2-by-2 matrix that contains at least two different values. The number of contour levels and the values of contour levels are chosen automatically based on the minimum and maximum values of Z. The ranges of the x- and yaxis are [1:n] and [1:m], where [m,n] = size(Z).
contour3(Z,n)

draws a contour plot of matrix Z with n contour levels in a 3-D view.

contour3(Z,v) draws a contour plot of matrix Z with contour lines at the values specified in vector v. The number of contour levels is equal to length(v). To draw a single contour of level i, use contour(Z,[i i]). Specifying the vector v sets the LevelListMode to manual to allow user control over contour levels. See contourgroup properties for more

information.
contour3(X,Y,Z), contour3(X,Y,Z,n), and contour3(X,Y,Z,v) draw contour plots of Z using X and Y to determine the x- and y-axis limits. If X is a matrix, X(1,:) defines the x-axis. If Y is a matrix, Y(:,1) defines the y-axis. When X and Y are matrices, they must be the same size as Z and must be monotonically increasing. contour3(...,LineSpec) draws the contour lines LineSpec. contour3 ignores marker symbols. contour3(axes_handle,...) into the current axes (gca).

using the line type and color specified by

plots into the axes with the handle axes_handle instead of

[C,h] = contour3(...)

returns a contour matrix, C, that contains the x, y coordinates and contour levels for contour lines derived by the low-level contourc function, and a handle, h, to an array of handles to graphics objects. The clabel function uses contour matrix C to label the contour lines. The graphic objects that contour3 creates are patch objects, or if you specify a LineSpec argument, line objects.

Examples
Plot the three-dimensional contour of a function and superimpose a surface plot to enhance visualization of the function.
[X,Y] = meshgrid([-2:.25:2]); Z = X.*exp(-X.^2-Y.^2); contour3(X,Y,Z,30) surface(X,Y,Z,'EdgeColor',[.8 .8 .8],'FaceColor','none') grid off view(-15,25) colormap cool

For more examples using contour3, see Contour Plots.

Contour Plots
On this page

Functions for Creating Contour Displays Creating Simple Contour Plots Labeling Contours Filled Contours Specifying Contour Levels Index Contours The Contouring Algorithm Changing the Offset of a Contour Displaying Contours in Polar Coordinates Preparing Data for Contouring

Functions for Creating Contour Displays


The contouring display functions compute, plot, and label isolines (contour lines) for one or more matrices. These displays vary according to whether they plot plain contour lines, filled contour lines, raised contours, or contours in concert with mesh or surface plots. Two of the functions support contouring. The low-level contourc function computes isolines but does not plot them. The clabel function places elevation labels on previously generated contours. Function
contour contour3 contourf contourc

Description Displays 2-D isolines generated from values given by a matrix Z. Displays 3-D isolines generated from values given by a matrix Z. Displays a 2-D contour plot and fills the area between the isolines with a solid color. Low-level function to calculate the contour matrix used by the other contour functions. Creates a mesh plot with a corresponding 2-D contour plot. Creates a surface plot with a corresponding 2-D contour plot. Generates labels using the contour matrix returned from calling the contouring function and displays the labels in the current figure.

meshc surfc clabel

Creating Simple Contour Plots

contour

and contour3 display 2-D and 3-D contours, respectively. They can be called with separate x, y, and z matrices, but need only one input argumenta z matrix interpreted as heights with respect to a plane. In this case, the contour functions determine the number of contours to display based on the minimum and maximum data values. To explicitly set the number of contour levels displayed by the functions, you specify a second optional argument.
Contour Plot of the Peaks Function

The statements
[X,Y,Z] = peaks; contour(X,Y,Z,20)

display 20 contours of the peaks function in a 2-D view.

The statements
[X,Y,Z] = peaks; contour3(X,Y,Z,20)

h = findobj('Type','patch'); set(h,'LineWidth',2) title('Twenty Contours of the peaks Function')

display 20 contours of the peaks function in a 3-D view and increase the line width to 2 points.

Labeling Contours
Each contour level has a value associated with it. clabel uses these values to display labels for 2-D contour lines. The contour matrix contains the values clabel uses for the labels. This matrix is returned by contour, contour3, and contourf and is described in The Contouring Algorithm.
clabel

optionally returns the handles of the text objects used as labels. You can then use these handles to set the properties of the label string. For example, display 10 contour levels of the peaks function:
Z = peaks; [C,h] = contour(Z,10);

Label the contours and display a title:


clabel(C,h) title({'Contour Labeled Using','clabel(C,h)'}) clabel

labels only those contour lines that are large enough to have an inline label inserted.

The 'manual' option enables you to add labels by selecting the contour you want to label with the mouse. You can also use this option to label only those contours you select interactively. For example:
clabel(C,h,'manual')

displays a crosshair cursor when your cursor is inside the figure. Pressing any mouse button labels the contour line closest to the center of the crosshair.

Filled Contours
The contourf displays a two-dimensional contour plot and fills the areas between contour lines. Use caxis to control the mapping of contour to color. For example, this filled contour plot of the peaks data uses caxis to map the fill colors into the center of the colormap:
Z = peaks; [C,h] = contourf(Z,10); caxis([-20 20]) title({'Filled Contour Plot Using','contourf(Z,10)'})

Specifying Contour Levels


The contouring functions permit you to specify the number of contour levels or the particular contour levels to draw. In the case of contour, the two forms of the function are contour(Z,n) and contour(Z,v). Z is the data matrix, n is the number of contour lines, and v is a vector of specific contour levels.

When you specify n (the number of contour levels to plot), you are setting the LevelStep property of the contourgroup. If you want to always draw n contour levels even when the data range of Z changes, obtain the contourgroup's handle and set its LevelStepMode to 'manual'. When you specify v (a vector itemizing contour levels), you are setting the contourgroup's LevelList property. By default, the LevelList is recomputed whenever contours are redrawn. If you always want to depict the same contour levels, even if the data changes, set the contourgroup's LevelListMode property to 'manual'.
Drawing a Single Contour

MATLAB functions do not differentiate between a scalar and a one-element vector. So, if v is a one-element vector specifying a single contour at that level, contour interprets it as the number of contour lines, not the contour level. Consequently, contour(Z,v) behaves in the same manner as contour(Z,n). To display a single contour line, define v as a two-element vector with both elements equal to the desired contour level. For example, create a 3-D contour of the peaks function:
xrange = -3:.125:3; yrange = xrange; [X,Y] = meshgrid(xrange,yrange); Z = peaks(X,Y); contour3(X,Y,Z)

To display only one contour level at Z = 1, define v as :


v = [1 1] contour3(X,Y,Z,v)

Example Visualizing Contour Construction

You can think of a contour as the intersection of a 3-D surface with a horizontal plane. The intersection defines 0 or more level lines that trace contours. The level lines either form loops or terminate at the outer edges of the surface. Contour loops can intersect at saddle points, and therefore require special handling in their vicinity. Run the following interactive code to visualize how contour lines are constructed. Use the slider to move the plane up or down through the range of z values, and click the Plot Contour button to draw a contour line that delineates where the plane slices through the surface. Click the Plot Labels button to add a label to the contour you just plotted. Click Clear Contours to remove all the contours and labels.
% Create x, y, and z arrays for a parametric surface [x y]=meshgrid(linspace(0,1,10),linspace(0,1,10)); z = .5*x + y - 1.5*x.*y; % Display with the surface function in 3-D fh = figure; colormap cool; hpl = uipanel(fh,'Units','normalized','position',[.025 .025 .95 .95]); s=surface('xdata',x,'ydata',y,'zdata',z,'cdata',z); view(3);hold on;

% Display a second surface, a horixontal plane at z = 0 p=surface('xdata',[0 1;0 1],'ydata',[0 0; 1 1],... 'zdata',[0 0; 0 0],'cdata',[0 0;0 0]); set(p,'facealpha',.25,'facecolor','red'); % Make cut plane transparent % Create a slider control for contour elevations hs = uicontrol(hpl,'style','slider','min',0,'max',100,... 'units','normalized','position',[.05 .05 .2 .05],... 'sliderstep', [.01 .05]); set(hs,'callback',... % Tell the slider what it should do ['lvl=get(hs,''value'')/100;,' ... 'set(p,''zdata'',[lvl lvl; lvl lvl]),' ... 'set(hto,''string'',num2str(lvl)),' ... 'set(hbc,''enable'',''on'')']); lvl = 0; % Initialize the z-level of the cutting plane % Create a label for the slider and a text box to show its value hst = uicontrol(hpl,'Style','text', 'String','Z-level',... 'units','normalized','Position',[.05 .10 .1 .05]); hto = uicontrol(hpl,'Style','text', 'String','0',... 'units','normalized','Position',[.13 .10 .1 .05]); % Create a pushbutton control for drawing contours with CONTOUR3 hbc = uicontrol(hpl,'style','pushbutton','enable','off',... 'string','Plot Contour',... 'units','normalized','position',[.80 .05 .15 .05]); set(hbc,'callback',['[C hc] = contour3(x,y,z, [lvl lvl],''r'');' ... 'set(hbl,''enable'',''on''), set(hbe,''enable'',''on''),' ... 'set(hbc,''enable'',''off'')']); % Create a pushbutton control for labelling with CLABEL, % which uses the "contour matrix" returned from CONTOUR3 hbl = uicontrol(hpl,'style','pushbutton','enable','off',... 'string','Plot Labels',... 'units','normalized','position',[.80 .90 .15 ,.05]); set(hbl,'callback',['clabel(C, hc,''color'',''r'',' ... '''fontweight'',''bold'');' 'set(hbl,''enable'',''off''), '... 'set(hbe,''enable'',''on'')']); % Create a pushbutton to clear away the contours and labels hbe = uicontrol(hpl,'style','pushbutton','enable','off',... 'string','Clear Contours',... 'units','normalized','position',[.05 .90 .15 .05]); set(hbe,'callback',['delete(findall(gca,''color'',''r''));' ... 'set(hbe,''enable'',''off'')']);

Here is what the figure and its controls look like with a contour plotted at the cut line.

See The Contouring Algorithm, below, for an explanation of how contour lines are computed.

Index Contours
You can index contours to visually emphasize certain contour levels. This technique, commonly used on topographic maps to highlight contours at set altitudes such as 25, 50, 75, ... meters above sea level, provides visual cues analogous to major ticks on a graph's axis. It is much easier to read a contour display that shows index contours because the heavier lines lessen the chance that your eye jumps between adjacent contours in scanning across the plot.
Example Specifying Index Contours

The following code example highlights contours at elevations of 6, 5, 4, ... 7 for the output of the peaks function. 1. Generate a data matrix to contour:
z = peaks(100);

2. Compute 40 contour levels. Select contour levels so as to be round numbers; zlevs is the vector of contour levels to be plotted:
3. zmin = floor(min(z(:))); zmax = ceil(max(z(:))); 4. zinc = (zmax - zmin) / 40; zlevs = zmin:zinc:zmax;

5. Specify the vertical distance between index contours; here it is unity, but it can be any modulus of values in zlevs.
zindex = 1;

6. Plot 2-D level lines with the contour function:


[c2,hc2] = contour(z,zlevs);

7. Create index contours by thickening level lines every zindex units:


8. nc = get(hc2,'Children'); 9. for i = 1:length(nc) 10. ud = get(nc(i),'UserData'); 11. if (mod(ud,zindex) == 0) 12. set(nc(i),'LineWidth',2); 13. end end

A contour line thickens with each call to set. 14. Annotate to identify the contouring parameters used:
15. s = sprintf('%s %g %s %g %s', 'Peaks Function Contoured at', ... 16. zinc, 'Units, Indexed every', zindex, 'Units'); title(s)

The loop of code in step 5 above works for contour but not forcontour3, because contour3 does not create contourgroup objects containing Children. To accomplish the same result with contour3, you must dereference the handle to the contours returned by contour3 (hc3, below) differently, as follows:

figure; [c3,hc3] = contour3(z,zlevs); for i = 1:length(hc3) ud = get(hc3(i),'UserData'); if (mod(ud,zindex) == 0) set(hc3(i),'LineWidth',2); end end s = sprintf('%s %g %s %g %s',... 'Peaks Function Contoured in 3-D at', ... zinc, 'Units, Indexed every', zindex, 'Units'); title(s)

The Contouring Algorithm


The contourc function calculates the contour matrix for the other contour functions. It is a low-level function that is not called from the command line. The contouring algorithm first determines which contour levels to draw. If you specified the input vector v, the elements of v are the contour level values, and length(v) determines the number of contour levels generated. If you do not specify v, the algorithm chooses no more than 20 contour levels that are divisible by 2 or 5. The height matrix Z has associated X and Y matrices that locate each value in Z at the intersection of a row and a column, or these matrices are inferred when they are unspecified. The row and column widths can vary, but typically they are constant (i.e., Z is a regular grid). Before calling contourc to interpolate contours, contourf pads the height matrix with an extra row or column on each edge. It assigns z-values to the added grid cells that are well below the minimum value of the matrix. The padded values enable contours to close at the

matrix boundary so that they can be filled with color. When contourc creates the contour matrix, it replaces the x,y coordinates containing the low z-values with NaNs to prevent contour lines that pass along matrix edges from being displayed. This is why contour matrices returned by contourf sometimes contain NaN values. Set the current level, c, equal to the lowest contour level to be plotted within the range [min(Z) max(Z)]. The contouring algorithm checks each edge of every square in the grid to see if c is between the two z values for the edge points. If so, a contour at that level crosses the edge, and a linear interpolation is performed:
t=(c-Z0)/(Z1-Z0) Z0

is the z value at one edge point, and Z1 is the z value at the other edge point.

Start indexing a new contour line (i = 1) for level c by interpolating x and y:


cx(i) = X0+t*(X1-X0) cy(i) = Y0+t*(Y1-Y0)

Walk around the edges of the square just entered; the contour exits at the next edge with z values that bracket c. Increment i, compute t for the edge, and then compute cx(i) and cy(i), as above. Mark the square as having been visited. Keep checking the edges of each square entered to determine the exit edge until the line(cx,cy) closes on its initial point or exits the grid. If the square being entered is already marked, the contour line closes there. Copy cx, cy, c, and i to the contour line data structure (the matrix returned by contouring functions, described shortly). Reinitialize cx, cy, and i. Move to an unmarked square and test its edges for intersections; when you find one at level c, repeat the preceding operations. Any number of contour lines can exist for a given level. Clear all the markers, increment the contour level, and repeat until c exceeds max(Z). Extra logic is needed for squares where a contour passes through all four edges (saddle points) to determine which pairs of edges to connect.
contour, contour3,

and contourf return a two-row matrix that specifies all the contour
xdata(1) ydata(1) xdata(2)... ydata(2)...]

lines:
C = [ value1 numv

The first row of the column that begins each definition of a contour line contains the contour value, as specified by v and used by clabel. Beneath that value is the number of (x,y) vertices in the contour line. Remaining columns contain the data for the (x,y) pairs. For example, the contour matrix calculated by C = contour(peaks(3)) is as follows.

The circled values begin each definition of a contour line.

Changing the Offset of a Contour


The surfc and meshc functions display contours beneath a surface or a mesh plot. These functions draw the contour plot at the axes' minimum z-axis limit. To specify your own offset, change the ZData values of the contour lines. First, save the handles of the graphics objects created by meshc or surfc:
h = meshc(peaks(20));

The first handle belongs to the mesh or surface. The remaining handles belong to the contours you want to change. To raise the contour plane, increment the z coordinate of each contour line by some amount by resetting its Zdata value:
for i = 2:length(h); newz = get(h(i),'Zdata') + 5; set(h(i),'Zdata',newz) end

Displaying Contours in Polar Coordinates


1. You can contour data defined in the polar coordinate system. As an example, set up a grid in polar coordinates and convert the coordinates to Cartesian coordinates.
2. [th,r] = meshgrid((0:5:360)*pi/180,0:.05:1); [X,Y] = pol2cart(th,r);

3. Then generate the complex matrix Z on the interior of the unit circle.
Z = X+i*Y; X, Y,

and Z are points inside the circle.

4. Create and display a surface of the function


5. f = (Z.^4-1).^(1/4); surf(X,Y,abs(f))

6. Display the unit circle beneath the surface and add labels to the graph:
7. hold on 8. surf(X,Y,zeros(size(X))) 9. hold off 10. xlabel('Real','FontSize',14); 11. ylabel('Imaginary','FontSize',14); 12. zlabel('abs(f)','FontSize',14);

Contours in Cartesian Coordinates

These statements display a contour of the surface in Cartesian coordinates and label the xand y-axis:
contour(X,Y,abs(f),30) axis equal

xlabel('Real','FontSize',14); ylabel('Imaginary','FontSize',14);

Contours on a Polar Axis

You can also display the contour within a polar axes. Create a polar axes using the polar function, and then delete the line specified with polar:
h = polar([0 2*pi], [0 1]); delete(h)

With hold on, display the contour on the polar grid:


hold on contour(X,Y,abs(f),30)

Preparing Data for Contouring


The various contour plotting functions, as well as the mesh and surface families of functions, accept 2-D matrices as inputs. For most applications, these input grids represent continuous functions of two variables or relatively continuous fields of data. In many applications, source data might consist of z values sampled over a two-dimensional domain in an irregular fashion, such as discrete spot elevations from GPS measurements (in the form of x, y, and z data vectors). To prepare such data for contour or mesh display, you need to interpolate it in some fashion. There are several MATLAB methods for interpolating data into vectors, grids, and triangulated (Delaunay) tessellations. Input observations can be one-, two-, three- or higherdimensional. By choosing and using these functions carefully you control parameters and constraints for interpolation to model your assumptions about the underlying nature of the raw data. Typically, you use the interp2, meshgrid, and TriScatteredInterp functions to interpolate z values for scattered x-y data points into a 2-D grid. See Interpolating Gridded Data and Interpolating Scattered Data for discussion and examples of data interpolation using these and other functions.

If the surface you are contouring is "noisy," contours depicting the surface exhibit jaggedness. When you analyze and explore such data, you can filter it to attentuate highfrequency variations. One way to do this is with a convolution (with conv2 or filter2) filter, as the following example demonstrates:
Example Smoothing a Matrix for Plotting Contours

The conv2 and filter functions can remove high-frequency components from a matrix representing a continuous surface or field to make the underlying data easier to visualize. 1. Create a function of two variables and plot contour lines at a specified, fixed interval:
2. 3. 4. 5. 6. 7. 8. 9. Z = peaks(100); figure; set (gcf,'position',[400,100,600,600], 'color','w') subplot(2,2,1); cl = [-7:1:10]; % Define contour levels for all plots contour(Z, cl) axis([0 100 0 100]); colormap autumn; set(gca,'Xtick',[0 100],'Ytick',[0 100]); title('Peaks Surface (underlying data)')

10. Add uniform random noise with mean of 0 to the surface and plot resulting contours. Irregularities in the contours tend to obscure the trend of the data:
11. 12. 13. 14. 15. ZN = Z + rand(100) - .5; subplot (2,2,2) contour(ZN, cl) axis([0 100 0 100]); set(gca,'Xtick',[0 100],'Ytick',[0 100]); title('Peaks Surface (noise added)')

16. Specify a 3-by-3 convolution kernal, F, for smoothing the matrix and use the conv2 function to attenuate high spatial frequencies in the surface data:
17. F = [.05 .1 .05; .1 .4 .1; .05 .1 .05]; ZC = conv2(ZN,F,'same');

18. Visually compare the smoothed surface to the original and the noisy ones:
19. 20. 21. 22. subplot (2,2,3) contour(ZC, cl) axis([0 100 0 100]); set(gca,'Xtick',[0 100],'Ytick',[0 100]); title('Noisy Surface (smoothed once)')

23. Smooth the surface one more time using the same operator and compare (a larger or more uniform kernal can achieve this in one pass):
24. 25. 26. 27. 28. ZC2 = conv2(ZC,F,'same'); subplot (2,2,4) contour(ZC2, cl) axis([0 100 0 100]); set(gca,'Xtick',[0 100],'Ytick',[0 100]); title('Noisy Surface (smoothed twice)')

surface
Create surface object

Syntax
surface(Z) surface(Z,C) surface(X,Y,Z) surface(X,Y,Z,C) surface(x,y,Z) surface(...'PropertyName',PropertyValue,...) h = surface(...)

Properties
For a list of properties, see Surface Properties.

Description
surface

is the low-level function for creating surface graphics objects. Surfaces are plots of matrix data created using the row and column indices of each element as the x- and ycoordinates and the value of each element as the z-coordinate.
surface(Z)

plots the surface specified by the matrix Z. Here, Z is a single-valued function, defined over a geometrically rectangular grid.
surface(Z,C)

plots the surface specified by Z and colors it according to the data in C (see

"Examples").
surface(X,Y,Z)

uses C = Z, so color is proportional to surface height above the x-y plane. plots the parametric surface specified by X, Y, and Z, with color specified

surface(X,Y,Z,C) by C.

surface(x,y,Z), surface(x,y,Z,C) replaces the first two matrix arguments with vectors and must have length(x) = n and length(y) = m where [m,n] = size(Z). In this case, the vertices of the surface facets are the triples (x(j),y(i),Z(i,j)). Note that x corresponds to the columns of Z and y corresponds to the rows of Z. For a complete discussion of parametric surfaces, see the surf function. surface(...'PropertyName',PropertyValue,...)

follows the X, Y, Z, and C arguments with property name/property value pairs to specify additional surface properties. For a description of the properties, see Surface Properties.
h = surface(...)

returns a handle to the created surface object.

Examples
This example creates a surface using peaks to generate the data, and colors it using the clown image. The ZData is a 49-by-49 element matrix, while the CData is a 200-by-320 matrix. You must set the surface's FaceColor to texturemap to use ZData and CData of different dimensions.
load clown surface(peaks,flipud(X),... 'FaceColor','texturemap',... 'EdgeColor','none',... 'CDataMapping','direct') colormap(map) view(-35,45)

Note the use of the surface(Z,C) convenience form combined with property name/property value pairs. Since the clown data (X) is typically viewed with the image command, which MATLAB normally displays with 'ij' axis numbering and direct CDataMapping, this example reverses the data in the vertical direction using flipud and sets the CDataMapping property to direct.

Setting Default Properties


You can set default surface properties on the axes, figure, and root object levels:
set(0,'DefaultSurfaceProperty',PropertyValue...) set(gcf,'DefaultSurfaceProperty',PropertyValue...) set(gca,'DefaultSurfaceProperty',PropertyValue...)

where Property is the name of the surface property whose default value you want to set and PropertyValue is the value you are specifying. Use set and get to access the surface properties.

You might also like