Plotting 3D
Plotting 3D
3D Plotting:
Figures with three dimensions are plotted in MATLAB using plot3 function
Plot3 (x,y,z, LineSpec) Produce plots according to the given coordinates in 3-D
space using the specified line style, marker and color. It is possible to plot multiple
plots on the same figure using Plot3 (x1, y1, z1, x2, y2, z2).
Ex: Draw a 3-D plot for 100 points between -5 and 5 for :
𝑎 = 𝑡𝑠𝑖𝑛(𝑡)
𝑏 = 𝑡𝑐𝑜𝑠(𝑡)
Use red line
Sol:
>> t=linspace(-5,5,100);
>> a=t.*sin(4*t);
>> b=t.*cos(4*t);
>> plot3 (a,b,t, 'r'); grid on
1
MATLAB
Sol:
>> t=-40:0.01:40;
>> a=sin(t);
>> b=cos(t);
>> plot3(t,a,b,'r--'); xlabel('t=-40:0.01:40'), ylabel('sin(t)'), zlabel('cos(t)'); grid on
H.w.: Plot the following figure
2
MATLAB
mesh(X,Y,Z) : produce mesh plot as a 3-D surface. The plot is given by matrix z as
heights of a grid in the x-y plane. The plot edges are colored according to the
heights given by z.
Ex: Use meshgrid function to generate three matrices with the same size using the
following limits and equations:
cos(𝑟)
𝑧=
𝑟
𝑟 = √(𝑥 2 + 𝑦 2 )
[𝑥, 𝑦] = −π: 0.2: π
Then plot them using mesh function.
Sol:
>> [x,y]=meshgrid (-pi:0.2:pi);
>> r=sqrt(x.^2+y.^2);
>> z=cos(r)./r;
>> mesh(x,y,z)
3
MATLAB
Sol:
>> [a,b]=meshgrid(-10:0.2:10);
>> c=a.^2+b.^2;
>> mesh(a,b,c); xlabel('amin=-10, amax=10'); ylabel('bmin=-10, bmax=10');
zlabel('c=a.^2+b.^2')
surf (x,y,z) : produce a 3-D plot as three dimensional surface. The plot is given by
matrix z as heights of a grid in the x-y plane. The plot edges are colored according
to the heights given by z.
Ex: Generate three matrices with the same size using the following limits and
equations:
2 −𝑦 2 )
𝑧 = 𝑥 2 𝑒 (−𝑥
[𝑥, 𝑦] = −π: 0.2: π
Then plot them using surf function.
4
MATLAB
Sol:
>> [x,y]=meshgrid(-pi:0.2:pi);
>> z=x.^2*exp((-x.^2-y.^2));
>> surf(x,y,z)
5
MATLAB
Bar charts
Bar (x,y)
Ex: for x=0.1 0.2 0.3 0.4 … 1 and y=4 8 2 1.5 7 5.3 1.2 0.9 4 4, draw bar chart.
Sol:
>> x=0.1:0.1:1;
>> y=[4 8 2 1.5 7 5.3 1.2 0.9 4 4];
>> bar (x,y); grid on
Contour line
A contour line of a function of two variables is a curve along which the function has
a constant value. It is a cross-section of the three-dimensional graph. Two data sets
x and y are needed. This is done by calling the meshgrid command.
Ex: For −5 ≤ x ≤ 5 and −3 ≤ y ≤ 3 with increment of 0.1 for both the values and
g=f(x,y)= x2 + y2 . Draw a contour line.
6
MATLAB
Sol:
>> [x,y] = meshgrid(-5:0.1:5,-3:0.1:3);
>> g = x.^2 + y.^2;
>> contour(x,y,g);