# Matlab – Generate Square Mesh, Given an Unordered X, Y and Z Vectors

matlab

I have three arrays of the same length in Matlab, `X`, `Y` and `Z`. `X(i)`, `Y(i)` and `Z(i)` forms a pair of 3D coordinates.

The issue now is, how to use these three arrays to generate square meshes, as shown below:

I got the image from mesh plot in Matlab documentation. So obviously `mesh` command is not what I want because it plots the meshes itself in the Matlab program, whereas I need the mesh elements ( along with the coordinates) so that I can plot them out myself in other program, such as C#.

In other words, I am looking for the mathematical algorithm to generate the meshes that allows `mesh` command to plot the below looking graph.

Edit: I realized that my question wasn't clear after a good night sleep. So here's more detail. I generate `x` and `y` vector by using this command `[x,y]=meshgrid[rangex, rangy]`, and then I define a vector z with the function `z(x,y)`. I would have to return a list of square elements ( as shown in the figure below) along with their corresponding `x`,`y` coordinates. So basically I just want to replot the following graph with those data.

Any ideas?

#### Best Solution

What you basically have are 3 matrices:

``````% define x_range and y_range as you wish
[x, y] - meshgrid(x_range,y_range)

z = some_function_of_x_and_y
``````

Now you have to reshape these three matrices into row vectors:

``````sizes = size(x)
x_row = reshape(x, sizes(1) * sizes(2), 1)
y_row = reshape(y, sizes(1) * sizes(2), 1)
z_row = reshape(z, sizes(1) * sizes(2), 1)
``````

and another one of indices:

``````indeces = [1:length(x_row)]'
``````

``````result = [indeces x_row y_row z_row]
``````

For instance:

``````x_range = [1,2,3];
y_range = [1,2,3];

>> [x,y] = meshgrid(x_range, y_range)

x =

1     2     3
1     2     3
1     2     3

y =

1     1     1
2     2     2
3     3     3

>> z = x+y

z =

2     3     4
3     4     5
4     5     6

>> x_row = reshape(x, sizes(1) * sizes(2), 1);
>> y_row = reshape(y, sizes(1) * sizes(2), 1);
>> z_row = reshape(z, sizes(1) * sizes(2), 1);

>> indeces = [1:length(x_row)]';

>> result = [indeces x_row y_row z_row]

result =

1     1     1     2
2     1     2     3
3     1     3     4
4     2     1     3
5     2     2     4
6     2     3     5
7     3     1     4
8     3     2     5
9     3     3     6
``````

Now `result` holds the indeces in the first column, and `(x,y,z)` in the rest of the columns. You should be able to extract what you want from there.