How to create 3D plots in Matlab.
3 steps are required:
1.- Define your area of operation, You need to use the meshgrid built-in function.
2.- Define your function z = f(x, y). You are working with matrices, not scalars, then use the dot operator to work element-by-element.
3.- Use 3D functions to plot: surf, surfc, mesh, contour, etc.
2. Task
Let’s say that you want to plot this equation:
𝑧 = cos 𝑥 cos 𝑦 𝑒
− 𝑥2+𝑦2
20
3. 3 Easy Steps to 3D-Plot
1. Define your grid to operate with. Use the
built-in function “meshgrid”.
2. Define your function z = f(x, y). Take into
account that you’re working with arrays,
not with scalars, use dot operators.
3. Use appropriate 3D built-in functions.
4. 1.- Define your Grid
Think:
• What values for x do I want to take into
account?
• What values for y do I need? Steps?
• Use “meshgrid” to create the appropriate
arrays.
5. 1.- Define your Grid
Let’s say that you are interested in this
portion of the function
−5 ≤ 𝑥 ≤ 5
−6 ≤ 𝑦 ≤ 6
6. 1.- Define your Grid
Think of lower and upper values, and steps
U = -5 : 0.2 : 5;
V = -6 : 0.2 : 6;
[x, y] = meshgrid(U, V);
Now, x and y are matrices with appropriate
values.
7. 2.- Define your Function
Enter your function as you would for any other
function in Matlab. Notice that you have to
use the dot operator to work with matrices.
z = cos(x) .* cos(y) .* exp(-sqrt(x.^2 + y.^2) / 20);
8. 3.- Use 3D built-in Functions
You can use functions such as:
surf
surfc
surfl
mesh
meshz
contour3
9. U = -5 : 0.2 : 5;
V = -6 : 0.2 : 6;
[x, y] = meshgrid(U, V);
z = cos(x) .* cos(y) .* exp(-sqrt(x.^2 + y.^2) / 20);
surf(x, y, z)
10. U = -5 : 0.1 : 5;
V = -6 : 0.1 : 6;
[x, y] = meshgrid(U, V);
z = cos(x) .* cos(y) .* exp(-sqrt(x.^2 + y.^2)/4);
surfc(x, y, z)
11. 3D Plots in Matlab
For more examples and details, visit:
matrixlab-examples.com/3D-plot-2tier.html