MATLAB Answers


Mesh for 3D plot

Asked by K
on 9 Jan 2013

Hello, I have set of data x,y and z. When I plotted the data by using command 'plot3', there is no problem. However, when I tried to plot it by using command 'mesh', there is problem occured:

Z must be a matrix, not a scalar or vector

Can anyone help me to plot the surface of 3D plot?


Log in to comment.


4 Answers

Answer by Amith Kamath on 9 Jan 2013
Edited by Amith Kamath on 9 Jan 2013

Going from the error, it seems that you are trying to use mesh for a 1D array (Z in your case). Mesh expects the 'Z' to be a 2D matrix containing all the values of the function, i.e. Z = f(x,y) as in the example from :

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;

So from : plot3(X1,Y1,Z1,...), where X1, Y1, Z1 are vectors or matrices, plots one or more lines in three-dimensional space through the points whose coordinates are the elements of X1, Y1, and Z1.

whereas from : mesh(X,Y,Z) draws a 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).

You got to make sure that size(Z) is [m,n]!


Log in to comment.

Answer by Ryan Livingston on 9 Jan 2013

A bit more detail would help in giving a precise answer. Including some example data or an example of a surface could assist folks in answering.

Generally for calling


there are a few possibilities.

  • x and y are vectors. Then, all of the pairs
(x(i), y(j)) for all i, j in range,

are taken to be your grid points. The value of the surface is then given by z(i,j) so that the points plotted are:

(x(i), y(j), z(i,j))
  • x and y are matrices. Then the points plotted are:
(x(i,j), y(i,j), z(i,j))

In each case, the vertical values in "z" need to be a matrix with one value per grid point in order to provide the right number of values.

A little example:

x = linspace(-10,10,100);
y = linspace(-10,10,100);
z = repmat(x,[100 1]);
z = z.^2;

  1 Comment

on 9 Jan 2013

The example of the data is like this:

DataA DataB DataC

0.06 0.14 0.5

0.07 0.15 0.5

0.08 0.19 0.5

0.06 0.13 1

0.08 0.15 1

Log in to comment.

Answer by lala
on 9 Feb 2013

Hi. Please clarify more! i have the same problem! Thanks!


Log in to comment.

Answer by lala
on 9 Feb 2013

Well, just a bit description: I have these points x, y, z points saying for example at x=2.5 and y=12, then z is 3:

x=[2.5 4 6 18 9]; y=[12 3 7.5 1 10]; z=[3 15 16 8 11.5];

and i want to create a 3D mesh.

I am able to create plot3 and/or scatter3 but not mesh :( please help! Thanks again!



Log in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today